• Marcelo Costa
  • NEWBIE
  • 110 Points
  • Member since 2016

  • Chatter
    Feed
  • 3
    Best Answers
  • 1
    Likes Received
  • 3
    Likes Given
  • 4
    Questions
  • 46
    Replies
I am trying to create a batch Apex class that I can schedule to run weekly to automatically unqualify Leads that are 60 days old or older and haven't had activity on them in the past 10 days (and only for a single Record Type). Here is my Class and Test Class...My assertion keeps failing. It seems 0 of my leads are being updated correctly.

Batch Apex Class:
global class AutoUnqualifyLeads implements Database.Batchable<sObject> {
    
    global Database.QueryLocator start(Database.BatchableContext bc){
        String query = 'SELECT Id, Status, Reason_Not_Qualified__c, LastActivityDate '+
                         'FROM Lead '+
                        'WHERE CreatedDate < LAST_N_DAYS:60 '+
                          'AND Days_Since_Last_Activity__c > 10 '+
                          'AND IsConverted = false '+
                          'AND Status != '+' \'Unqualified\' '+
                          'AND RecordTypeId = '+' \'0121I000000QxE7QAK\' ';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext bc, List<Lead> scope){
        List<Lead> leads = new List<Lead>();
        for (Lead l: scope){
                l.Status                  = 'Unqualified';
                l.Reason_Not_Qualified__c = 'No Response';
                system.debug(l);
                leads.add(l);
        }
   update leads;
   }

    global void finish(Database.BatchableContext bc){
        
    }
}

Test Class (my test load data information is listed below the code snippet):
@isTest

private class AutoUnqualifyLeadsTest {
    @isTest
    static void setupTest(){
        List<Lead> leadLoad = Test.loadData(Lead.sObjectType,'testLeadsAutoUnqual');
        System.debug(leadLoad);
        
    }
    
    @isTest
    static void testLeads(){
        
        Test.startTest();
        AutoUnqualifyLeads aul = new AutoUnqualifyLeads();
        Id batchId = Database.executeBatch(aul);
        Test.stopTest();

     System.assertEquals(3, [select count() from Lead where Status='Unqualified']);
    }
 
}
Test data:

CreatedDate, RecordTypeID, Days_Since_Last_Activity__c, Status, Reason_Not_Qualified__c, LastName, Company
2017-10-07T01:40:39, 0121I000000QxE7, 12, Open, Bing, Friends Co.
2017-09-22T01:43:39, 0121I000000QxE7, 13, Contacted, Gellar, Friends Inc.
2014-05-02T02:43:39, 0121I000000QxE7, 4, Open, Green, Friends LLC

Can you please help me troubleshoot??
 
I am super new to Apex and consequently struggling through. I created an Apex class with the intent that I will trigger it with Process Builder. I built a test class for it and I'm getting the error "Method does not exist or incorrect signature: void updateCustomer(Id) from the type CustomerAccountingUpdate.

Here's my Apex Class:
public class CustomerAccountingUpdate {
        
    public static string updateCustomer(Account aAccount) {
    	aAccount.c2g__CODAAccountsReceivableControl__c = System.Label.GeneralLedgerAcctsRec;
        aAccount.c2g__CODASalesTaxStatus__c = 'Taxable';
        aAccount.c2g__CODATaxCode1__c = 'AvaTax';
        aAccount.c2g__CODADaysOffset1__c = 0;
        aAccount.c2g__CODADescription1__c = 'Due Upon Receipt';
       
        update aAccount;
        
        return 'success';
    }
}


And my test Class:
@isTest(SeeAllData=true)
public class CustomerAccountingUpdateTest {
	static private Account setUpTestEnvironment() {          
         Account a =  new Account(
                               Name = 'Test Accounting Test'
                               ,Type = 'Prospect'            				   
                           );
         insert a;
        return a;
    }
    static testMethod void AccountingUpdateTest() {
         Account a = setUpTestEnvironment();
   
         Test.startTest();
         
         CustomerAccountingUpdate.updateCustomer(a.id);
         
         Test.stopTest();
    }
}


Thanks so much - this is the first time I've written a class & test totally from scratch rather than modifying something that was already there so I have no idea where I'm going wrong.
 
Hello,

Admin here so apologies for any inaccurate terminology on my part.

We have an Apex class with a @future tag that has been responsible for creating a scheduled apex class to change the ownership on a newly created record. This process for the most part has worked without a hitch, though recently we had a couple of snags we can't explain.

The first thing that happens is that while the Scheduled Apex class will be listed as "Completed" in the Apex Jobs Queue, that status will then change to "Aborted" the next time that apex class is called for a new record (which will itself be listed as "Completed" until the next job is called). This doesn't appear to affect functionality at all, but it somewhat strange.

The second thing that happens is that, out of the blue, an Apex job a few days ago got stuck at "Queued" for no particular reason and never fired(causing the ownership of the record to stay the same). By all accounts this hasn't happened before, and we have no idea what could have caused it since there wasn't really anything unusual with the record or the system going on at the time (we tried it again with an identical record and it worked perfectly). 

Any idea why this could be happening? We haven't encountered problems like this before and our development company is stumped. I'd be happy to provide Apex Code/Debug Logs if necessary.

Thank you,
Max

Hi everyone.
I have something that never happened with us before, and I wonder if anyone can help me. adding a contract related list to an account object for a specific page layout, ended up showing the contracts related list with 2 columns... have never seen that before and do not know how to fix it.
Anyone knows how to "fix" it (display the fields in a table as per default behavior??)

Related list of Contracts in account related tab.

Hi Everyone,
I have a issue in a customer, where we have 2 portals installed, and 2 different sso solutions at the same time.
Regular salesforce users log in through login.salesforce.com or custom url.
Customers from portal 1 go through IDP 1
Customer from portal 2 o trough IDP 2
Both IDP SSO configs are SP initiated (they have to start on salesforce).
My issue is:
I need a way to avoid going to the login page and actively chose one of the logins methods.
Salesforce generate the login links as follows:

https://my.custom.salesforce.domain/saml/authn-request.jsp?saml_request_id=_2CAAAAVZTcY0mME8wbTAwMDAwMDA0Qzk0AAAAypQs87MjXfKGfnOM29wBsHYId_Alz7ZZxK9jm0Sw2ElCsi4NGRR0OeIj1-asA8CLNDxFCpFjK3Cu4pxu031lK7RQaxwGRPuw4eI9nnPtleFYfR_5_eIXAAE0Dcp7zHjceZXj1q7Ivl5_Prgc0wDl7YmXkt53qOVr8bJ2oAPtR-CMj-_XB_KDi7URAcJnjWDvsseG0z15wSpCwN52nhB9QzWJWwvZTJ0BwYxS9ex4PJHrP8UPSS-pgnBiiG9oPLQp5g&saml_acs=https%3A%2F%2Fmy.custom.salesforce.org%3Fso%3D00Dm0000000CqC7&saml_binding_type=HttpPost&Issuer=https%3A%2F%2F.my.salesforce.com%2F&samlSsoConfig=SSoCOnfigId&RelayState=%2F

Is there a way to programatically chose a connection method or to manually generate the saml_request_id
Anyone has any thoughts on how achieve that without going the IDP initiated SSO???
Cheers
Dears,
I am having a really big problem trying to add pages to a customer community using the napili template when trying to add a menu item of a community page type. When I select the page here is what I get:
User-added image

If I remove the : from objectname and filterId, I can add the Item, but when I try to access the page It transfers me to the error page.
Anyone ever managed to get that working??
Best Regards.
Hey All!
We are facing a issue here trying to use standard svg icons on tabs in console.
We can easily set the icon (default service cloud console case) using:
sforce.console.setTabIcon('/img/icon/t4v35/standard/case_60.png', null, null);
But the thing is that afterwards we should set the other attributes (background color for icon etc..)
Has anyone achieved that?
Best regards!!

 
Hey All!
We are facing a issue here trying to use standard svg icons on tabs in console.
We can easily set the icon (default service cloud console case) using:
sforce.console.setTabIcon('/img/icon/t4v35/standard/case_60.png', null, null);
But the thing is that afterwards we should set the other attributes (background color for icon etc..)
Has anyone achieved that?
Best regards!!

 
My Salesforce Developer Edition (DE) org will be locked within the coming days, unless I can log-in to reactivate it. How can I log-in to reactivate it? What is the URL to do that? It's urgent, so any other relevant info will help. Thank you.

I looked through Q&A docs but couldn't seem to resolve the issue so far.
I need to send some data to the accounting system that my company uses. It has a public API and endpoint where I can ping it with an XML message. 

If I was just going to send Opportunities, then I could just use Outbound Message in a simple way. 

However, I need to send Opportunities and some LineItems. I need to bundle this data together. 

I'm wondering how should I handle this? Should I write custom Apex code? Or can I do this as a Flow? Is there a simple way to do this using Outbound Message? 
public class StageGateTaskController 
{   
    @AuraEnabled
    public static List<StockRequestWrap> getStageGate(String recordId, string stage)
    {
        System.debug(recordId+stage);
        if(stage=='Ideation')
        {
            stage='Ideation Stage';    
        }
        //User u = [Select Department From User Where id = :UserInfo.getUserId()];
        //String dept = u.Department;
        
        List<Stage_Gate_Task__c> task1=[select Id,User__c,Due_Date__c,Subject__c,Comment__c,Department__c,Task_status__c,CreatedDate,LastModifiedDate,Completed_Date__c from Stage_Gate_Task__c where Stage_Gate__c=:recordID and Stage__c=: stage ];
        system.debug('task'+task1);
        //system.debug('Completed_Date__c'+task1[0].Completed_Date__c);
        List<StockRequestWrap> stockReqwrap1 = new List<StockRequestWrap>();
        for(Stage_Gate_Task__c task: task1)
        {
            
            //System.debug('created Date'+task.CreatedDate.format('yyyy-MM-dd'));
            StockRequestWrap stockReqwrap = new StockRequestWrap();
            stockReqwrap.sobjectType = 'Stage_Gate_Task__c';
            stockReqwrap.Id = task.Id;
            stockReqwrap.AssignTo = task.User__c;
            stockReqwrap.DueDate = task.Due_Date__c;
            stockReqwrap.AssignDate = date.newinstance(task.CreatedDate.year(), task.CreatedDate.month(), task.CreatedDate.day());
            stockReqwrap.completionDate = task.Completed_Date__c;
            stockReqwrap.Subject = task.Subject__c;
            stockReqwrap.Description = task.Comment__c;
            stockReqwrap.Dept = task.Department__c;
            stockReqwrap.Status = task.Task_status__c;
            
            stockReqwrap1.add(stockReqwrap);
        }
        system.debug('stockReqwrap1'+stockReqwrap1); 
        
        return stockReqwrap1; 
    }
    public class StockRequestWrap{
        @AuraEnabled
        public id Id{get;set;}
        @AuraEnabled
        public String sobjectType{get;set;}
        @AuraEnabled
        public String AssignTo{get;set;}
        @AuraEnabled
        public Date DueDate{get;set;}
         @AuraEnabled
        public Date AssignDate{get;set;}
         @AuraEnabled
        public Date completionDate{get;set;}
        @AuraEnabled
        public String Subject{get;set;}
        @AuraEnabled
        public String Description{get;set;}
        @AuraEnabled
        public String Dept{get;set;}
        @AuraEnabled
        public String Status{get;set;}
    }
    @AuraEnabled
    public static List<ContentDocument> getFiles(String recordId, string Title,string Title1){ 
        system.debug('recordId'+recordId);
        ID filter = recordId;
        List<ContentDocumentLink> cdlList = [SELECT Id, LinkedEntityId, ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId=:filter];                         
        Set<Id> documentIds = new Set<Id>(); 
        
        for(ContentDocumentLink cdl:cdlList){  
            documentIds.add(cdl.ContentDocumentId); 
            
        }  
        if(Title!=null){
            ContentDocument docList= [SELECT Id, Title, FileType FROM ContentDocument WHERE Id IN :documentIds order by createddate DESC limit 1];
            if(docList!=null){
                docList.Title=Title;
                update docList;
            }
            
        }
        if(Title1!=null){
            ContentDocument docList= [SELECT Id, Title, FileType FROM ContentDocument WHERE Id IN :documentIds order by createddate DESC limit 1];
            if(docList!=null){
                docList.Title=Title1;
                update docList;
            }
        }
        //public link creation
        //Delete Pre Public link
          list<ContentDistribution> prev =[select DistributionPublicUrl,Name from ContentDistribution where ContentDocumentId = :documentIds];
        delete prev;
        
        list<ContentDocumentLink> cdl = [select contentdocument.id, contentdocument.title, contentdocument.filetype from contentdocumentlink where linkedentityid = :filter];
        list<ContentVersion> cv = [select id,contentdocumentid from contentversion where contentdocumentid =: documentIds];
      
        
        system.debug('cdl'+cdl.size()+'cv'+cv.size());
        system.debug('documentIds'+documentIds);
        list<ContentDistribution> cdList = new list<ContentDistribution>();
        integer i=0;
        for(ContentDocumentLink conDL:cdl)
        {      
             
                    ContentDistribution cd = new ContentDistribution();
                    cd.Name = conDL.contentdocument.title;
                    cd.ContentVersionId = cv[i++].id;
                    cd.PreferencesAllowViewInBrowser= true;
                    cd.PreferencesLinkLatestVersion=true;
                    cd.PreferencesNotifyOnVisit=false;
                    cd.PreferencesPasswordRequired=false;
                    cd.PreferencesAllowOriginalDownload= true;
                      System.debug(cd);
                    cdList.add(cd);
                
              
        }
        
       
        insert cdList;
        /*ContentDistribution cd = new ContentDistribution();
        cd.Name = cdl.contentdocument.title;
        cd.ContentVersionId = cv.id;
        cd.PreferencesAllowViewInBrowser= true;
        cd.PreferencesLinkLatestVersion=true;
        cd.PreferencesNotifyOnVisit=false;
        cd.PreferencesPasswordRequired=false;
        cd.PreferencesAllowOriginalDownload= true;
        insert cd;*/
        System.debug([SELECT Id, Title, FileType FROM ContentDocument WHERE Id IN :documentIds]);
        return [SELECT Id, Title, FileType FROM ContentDocument WHERE Id IN :documentIds];        
    } 
    
    @AuraEnabled
    public static List<ContentVersion> getContents(Id FileRecordId) {
        /*    Set<Id> contentIds = new Set<Id>();

for (ContentDocument cont :[Select Id ,Title from ContentDocument where ]) {
contentIds.add(cont.Id);
}

return [SELECT Id,Title FROM ContentVersion WHERE ContentDocumentId IN :contentIds];*/
        return null;
    }
    
    //Get Files
    @auraEnabled
    public static List<ContentDocument> getTaskFiles( String FileRecordId){ 
        
        System.debug('Request from Task '+FileRecordId);
        ID filter = FileRecordId;
        
        List<ContentDocumentLink> cdlList = [SELECT Id, LinkedEntityId, ContentDocumentId FROM ContentDocumentLink WHERE LinkedEntityId=:filter];                         
        Set<Id> documentIds = new Set<Id>(); 
        
        for(ContentDocumentLink cdl:cdlList){  
            documentIds.add(cdl.ContentDocumentId);  
        } 
        System.debug([SELECT Id, Title, SystemModStamp FROM ContentDocument WHERE Id IN :documentIds]);
        return [SELECT Id, Title, SystemModStamp FROM ContentDocument WHERE Id IN :documentIds and (NOT Title like '%Due_Date_Attachement%')]; 
        
    } 
    @AuraEnabled
    public static void submitapproval(Id recordId){ 
        Messaging.CustomNotification notification = new Messaging.CustomNotification();
        notification.setBody('Process owner submitted for Approval!');
        notification.setTitle('Process owner submitted for Approval!');
        notification.setSenderId(Userinfo.getUserId());
        CustomNotificationType type = [SELECT Id FROM CustomNotificationType WHERE DeveloperName = 'stageGateApproval'];
        notification.setNotificationTypeId(type.id);
        notification.setTargetId(recordId); // target object id
        notification.send(new Set<String> { '0052w000007ryisAAA' });
        
    }
   @AuraEnabled
    public static string processEmail(String Subject, String Message,Id RecordId,string Stage){
        String sMessage='';
        try{
            List<Gate_Keeper__c> gateKeepers = [select Id,Name,Users__c,Stage__c,Stage_Gate__c,Users__r.Email__c from Gate_Keeper__c where Stage_Gate__c=: RecordId];
            //system.debug(gateKeeper.Users__r.Email__c);
            for(Gate_Keeper__c gateKeeper:gateKeepers ){
            
               string Messages=Message+'&GId='+gateKeeper.Id;
              string email = gateKeeper.Users__r.Email__c;
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            String[] toAddresses = new String[] {email}; 
            mail.setToAddresses(toAddresses);
            mail.setSubject(Subject);
            mail.setHtmlBody(Messages);
            Messaging.SendEmailResult [] results = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {mail});
            sMessage='Success';  
            }
            /*List<Gatekeeper_QS__c> gatekeeper1 = [select Id,Name,Mail_send__c from Gatekeeper_QS__c where Stage__c=:Stage and Stage_Gate__c=:RecordId];
            if(gatekeeper1.size()>0)
            {
                gatekeeper1[0].Mail_Send__c = true;
                update gatekeeper1;   
            }*/
            
        }
        catch(Exception ex){
            sMessage=ex.getLineNumber()+'\n'+ex.getCause()+'\n'+ex.getMessage()+'\n'+ex.getStackTraceString();
            system.debug('sMessage'+sMessage);
        }
        return sMessage;
    } 
     @AuraEnabled
    public static string getApprovalStatus(String recordId, string stage)
    {
        Gate_Keeper__c GateKeeper = [SELECT id, name, Ideation_Stage_Comments__c,Stage_Gate__c,Stage__c,Business_Case_Response__c,Developer_Response__c,Ideation_Stage_Response__c,Scope_Response__c,Sign_off_Launch_Response__c,Test_Validate_Response__c FROM Gate_Keeper__c WHERE Stage_Gate__c=: recordId and Stage__c=: stage limit 1];
        string status;
        if(stage == 'Ideation Stage')
            {
                status = GateKeeper.Ideation_Stage_Response__c;
            }
            
            if(stage == 'Scope')
            {
               status = GateKeeper.Scope_Response__c;
            }
            
            if(stage == 'Business Case')
            {
                status = GateKeeper.Business_Case_Response__c;
            }

            if(stage == 'Develop')
            {
               status = GateKeeper.Developer_Response__c;
            }
           
            if(stage == 'Test & Validate')
            {
               status = GateKeeper.Test_Validate_Response__c;
            }
           
            if(stage == 'Sign Off & Launch')
            {
               status = GateKeeper.Sign_off_Launch_Response__c;
            }
        return status;
    }
    
   @AuraEnabled
    public static string RecordId(string stage)
    {
      Id devRecordTypeId = Schema.SObjectType.Stage_Gate_Question__c.getRecordTypeInfosByName().get(stage).getRecordTypeId();
        system.debug('devRecordTypeId'+devRecordTypeId);
       return devRecordTypeId;  
    }
    /*@AuraEnabled
    public static List<ApproverDetails>ApproverDetails(string recordId,string stage)
    {
        Stage_Gate__c approval = [select Id,Name,Approved_By__c,CEO__c,Issued_By__c,Marketing_Head__c from Stage_Gate__c where Id=:recordId];
        List<ApproverDetails> Details = new  List<ApproverDetails>();
        ApproverDetails a = new ApproverDetails();
        a.Approved=approval.Approved_By__c;
        a.CEO=approval.CEO__c;
        a.Issued=approval.Issued_By__c;
        a.MarketingHead=approval.Marketing_Head__c;
        Details.add(a);
        return details;
    }
    public class ApproverDetails{
        @AuraEnabled
       public string Approved{get;set;}
         @AuraEnabled
       public string CEO{get;set;}
        @AuraEnabled
       public string Issued{get;set;}
        @AuraEnabled
       public string MarketingHead{get;set;}
        
    }*/
    /*@AuraEnabled
    public static string GatekeeperRecordId(string stage)
    {
      Id devRecordTypeId = Schema.SObjectType.Stage_Gate_Question__c.getRecordTypeInfosByName().get(stage).getRecordTypeId();
        system.debug('devRecordTypeId'+devRecordTypeId);
       return devRecordTypeId;  
    } */
}
Hello and thanks for reading!
I have a section in the Contact layout with these fields:

Opt out of Email
Do Not Call
Do Not Contact

I've added a checkbox called Lead Only/No Auto Emails. As users manually add new Contacts, they'll be checking that to prevent them from receiving automated communication.
The idea is to set up a new flow. When a contact makes a donation for the first time, automatically uncheck that box.

We are using SFDC's BCC Email-To-Salesforce feature, often creating new contacts with it. Is it possible to know that a contact originated from one of those emails and automatically check the box?

The problem with defaulting it as checked is that there are a lot of integrations creating new contacts in this setup: donations, text messages, Facebook ads/leads, web forms, etc. I would need to update all of them to explicitly UNcheck that box.

I have a schedulable batch class which is stateful. In execute am inserting upto 1000 records.

In final method  i have a list of ids of inserted record

global void finish(Database.BatchableContext BC)
  {
                    if(Ids.size()>0)
                    {
                      for(string id : Ids)
                      {
                        // calling a static method sending id as paramter.
                      }
                    }
 
  }


In for loop for every id calling an static method with id as parameter.

The call static method will created an instance of another class which has nearly 10 queries and an http request.

am getting Too many SOQL queries: 201 

This is my static method

global  class SClass
{
  
  public static void SMethod(String id)
  {      
                         
       
         Sclass2 s = new sclass2 (Id,false);
         s.test();// this method has http request
   }           
        
}
 

why do i get this even when we have created new instance for every id. 

Any solution please.

Thanks,

 

I need to publish code coverage to Azure DevOps build pipeline. It needs ot be in Cobertura or JaCoCo format. Are there any tools I could use to convert current format into somehting that AzureDO can process?

I execute this command to generate code coverage:

sfdx force:apex:test:run --wait 10 --resultformat junit --codecoverage

test results are viewable in the pipeline, but not coverage...
I have a change set I'm trying to validate and I get the following error and I don't understand what it means.  There is one custom lookup field in the change set. 

duplicate value found: <unknown> duplicates value on record with id: <unknown>


Thanks in advance for your help!
Following the latest release, the hyperlink functionality we have been using to link agents to the telephony app and to create a new task linked to the lead they are dialling off stopped working.

I have been trying to create a new custom link within the lead layout, but I cannot get it to link to the Lead.  
Here is what I have currently:

https://eu1.salesforce.com/00T/e?Task.Subject=Call&Task.Who={!Lead.Id}&followup=1&tsk5=Call&retURL=%2F{!Lead.Id}&Task.Number_Dialled__c=&{!Lead.MobilePhone}&Task.Call_Source__c=Outbound;

window.open('https://xxxxx.xxxx.net.nz/Dialer/Phone/"&{!Lead.MobilePhone}&"','DiallerWindow','status = 1, height = 500, width = 500, resizable = 1');

When I click the custom link, a new task is created but it is not linked to the lead I came from, and the dialler piece does not work.

Help?!

 
this.SBAAcctLst.add(new SBARelation(0, new Account(RecordTypeId = accRtSBAId,Owner_Fulfillment_Account__c=null, Phone_Type__c='Work',
                                            ShippingStreet=NSBAAcctLst[0].NSBA.ShippingStreet, 
                                            ShippingCity=NSBAAcctLst[0].NSBA.ShippingCity,
                                            ShippingState=NSBAAcctLst[0].NSBA.ShippingState,
                                            ShippingCountry=NSBAAcctLst[0].NSBA.ShippingCountry,
                                            ShippingPostalCode=NSBAAcctLst[0].NSBA.ShippingPostalCode), this));
I am trying to create a Trigger to limit the number of Account a User can own.
Here is my code:
trigger Accounts75Limit on Account (after insert, after update) {

    //List<Account> acc = new List<Account>();
	for(Account acc : trigger.new)
    string accountOwner = accs.OwnerId;

    if (accs.Protected_Accounts__c == true) {
        Integer accounts = [ SELECT COUNT()FROM Account WHERE Account.OwnerId = : accountOwner]; 
        system.debug(accounts);

        if (accounts >3 ) {
            accs.addError('You are your limit of Accounts.');
        }
    }
}

I am getting the following errors:
User-added image

Any ideas?

Thanks!
I am trying to create a batch Apex class that I can schedule to run weekly to automatically unqualify Leads that are 60 days old or older and haven't had activity on them in the past 10 days (and only for a single Record Type). Here is my Class and Test Class...My assertion keeps failing. It seems 0 of my leads are being updated correctly.

Batch Apex Class:
global class AutoUnqualifyLeads implements Database.Batchable<sObject> {
    
    global Database.QueryLocator start(Database.BatchableContext bc){
        String query = 'SELECT Id, Status, Reason_Not_Qualified__c, LastActivityDate '+
                         'FROM Lead '+
                        'WHERE CreatedDate < LAST_N_DAYS:60 '+
                          'AND Days_Since_Last_Activity__c > 10 '+
                          'AND IsConverted = false '+
                          'AND Status != '+' \'Unqualified\' '+
                          'AND RecordTypeId = '+' \'0121I000000QxE7QAK\' ';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext bc, List<Lead> scope){
        List<Lead> leads = new List<Lead>();
        for (Lead l: scope){
                l.Status                  = 'Unqualified';
                l.Reason_Not_Qualified__c = 'No Response';
                system.debug(l);
                leads.add(l);
        }
   update leads;
   }

    global void finish(Database.BatchableContext bc){
        
    }
}

Test Class (my test load data information is listed below the code snippet):
@isTest

private class AutoUnqualifyLeadsTest {
    @isTest
    static void setupTest(){
        List<Lead> leadLoad = Test.loadData(Lead.sObjectType,'testLeadsAutoUnqual');
        System.debug(leadLoad);
        
    }
    
    @isTest
    static void testLeads(){
        
        Test.startTest();
        AutoUnqualifyLeads aul = new AutoUnqualifyLeads();
        Id batchId = Database.executeBatch(aul);
        Test.stopTest();

     System.assertEquals(3, [select count() from Lead where Status='Unqualified']);
    }
 
}
Test data:

CreatedDate, RecordTypeID, Days_Since_Last_Activity__c, Status, Reason_Not_Qualified__c, LastName, Company
2017-10-07T01:40:39, 0121I000000QxE7, 12, Open, Bing, Friends Co.
2017-09-22T01:43:39, 0121I000000QxE7, 13, Contacted, Gellar, Friends Inc.
2014-05-02T02:43:39, 0121I000000QxE7, 4, Open, Green, Friends LLC

Can you please help me troubleshoot??
 
Hello,

I'm not sure why the trigger is not triggering the Case assignment rules. I've checked other posts and have tried to requery my list and I'm still unable to get the Case Assignment Rule to work. 
 
public class Case_RunAssignmentRule {

	public static void runCaseAssignmentRules(List<Case> caseList) {

		List<Case> caseToUpdate = new List<Case> ();
		Id caseInboundRecordType = Schema.SObjectType.Case.getRecordTypeInfosByName().get('Inbound Case').getRecordTypeId();

		for (Case c : caseList) {
			if (c.RecordTypeId == caseInboundRecordType) {
				caseToUpdate.add(c);
				System.debug('CaseID --> ' + caseToUpdate);
			}

		}

		if (caseToUpdate.size() > 0) {
			//List<Case> caseToRunAssignment = [SELECT Id, OwnerId FROM Case WHERE Id IN :caseToUpdate];


			Database.DMLOptions dmo = new Database.DMLOptions();
			dmo.assignmentRuleHeader.useDefaultRule = true;
			System.debug('DMO --> ' + dmo);

			for (Case caseL : caseToUpdate) {
				caseL.setOptions(dmo);
				System.debug('caseOwner --> ' + caseL.OwnerId);
				System.debug('caseId --> ' + caseL);
			}

			//insert caseToUpdate;

		}
	}
}
@isTest
public class Case_RunAssignmentRuleTest {

	@testSetup static void setupTest() {
		List<TriggerController__c> tc = new List<TriggerController__c> {
			new TriggerController__c(Name = 'Case', Disabled__c = false)
		};
	}

	static testmethod void newCaseInsert() {
        
		List<Case> newCases = new List<Case> ();
		for (Integer i = 0; i<5; i++) {
			Case c = new Case();
			c.Subject = 'InboundCaseForCAR' + i;
			c.Product__c = 'G2M';
			c.Reason_Category__c = 'Admin Change';
			c.Case_Category__c = 'Contract Services';
			c.Status = 'New';
            c.RecordTypeId = '01213000001ZUeG'; 
			newCases.add(c);
		}

		test.startTest();
		insert(newCases);

		Id currentUserId = UserInfo.getUserId();

		List<Case> returnCaseList = [SELECT Id, OwnerId, Subject FROM Case WHERE Id IN :newCases];
		for (Case c : returnCaseList) {
			System.assertNotEquals(currentUserId, c.OwnerId);
			System.assertEquals(5, returnCaseList.size());
		}
		test.stopTest();
	}
}


 
  • December 07, 2017
  • Like
  • 0
Hi MVPs and Salesforce experts,

I have got a complecrequirement here. How can I integrate multiple salesforce orgs(may be 100s) and get the data into a single org? 
Any help is really appreciated.
Here is my code. I can not even save this because the related object is not being located. 
I'm trying to generate a list of related payments for an Opportunity. (not sure if it matters, but our org renamed Opportunities to Income)...what's going on? I keep getting this message: "Error: Invalid field OppPayments for SObject Opportunity"
 
<messaging:emailTemplate 
recipientType="Contact" 
relatedToType="Opportunity"
subject="Payment report for Opportunity: {!relatedTo.name}"
replyTo="n.wylder@ifiusa.org">
    <messaging:htmlEmailBody>
        <html>
            <body>

            <p>Dear {!recipient.name},</p>
            <p>Below is a list of payments related to {!relatedTo.name}.</p>
            <table border="0" >
                <tr>
                    <th>Case Number</th><th>Origin</th>
                    <th>Creator Email</th>
                </tr>
                <apex:repeat var="cx" value="{!relatedTo.OppPayments}">
                <tr>
                    <td><a href = 
                        "https://na77.salesforce.com/{!cx.id}">{!cx.Name}
                    </a></td>
                    <td>{!cx.Designation__c}</td>
                    <td>{!cx.npe01__Payment_Amount__c}</td>
                </tr>
                </apex:repeat> 
            </table>
            <p/>
            <center>
                <apex:outputLink value="http://www.salesforce.com">
                    For more detailed information login to Salesforce.com
                </apex:outputLink>
            </center>
            </body>
        </html>
    </messaging:htmlEmailBody>
</messaging:emailTemplate>

 
We are using Single sign on to login to Salesforce. We'd like to make an API callout from Salesforce to an internal API. To authenticate to access the API, we'd like to use the session token from the single sign-on to send with the HttpRequest so that the service can validate that the request is coming from a reliable user from salesforce. How to get the user session token that the single sign-on provider sends using Apex?

Any guidance would be helpful. Thank you!
 
  • December 06, 2017
  • Like
  • 0

Greetings,

 

I wrote this little loop while trying to get a list of ALL accounts within a Hierachy regardless of there in the hierachy you start from.

 

For example

A

-----b

-----------b1

-----c

-----------c1

---------------c1.2

-----d

 

So if I start at b1, it will return all accounts up to A and back down thus including c1.2 as well.

 

Maybe someone will find it useful. You could refactor it to work with roles or only go up 1 level to find parent and siblings, etc...

 

 

Account theAccount = //Your SOQL Here
Set<ID> AllParents = new Set<ID>();
Boolean allDone;

AllParents.add(theAccount.ID);
      //If the account we are starting at has a Parent ID, add it
      //to the set of IDs
      if(theAccount.ParentID != Null){
        AllParents.add(theAccount.ParentID);
      }
      
      //Main loop to traverse through the Hierarchy
      do{
         //Set the flag to indicate loop should stop
         allDone = true;
        //Get a list of accounts with IDs or Parent IDs in the AllParents Set
        //This will produce 1 SOQL for each level in the Hierachy 
        //Max is then 99 levels deep which I believe no one will  have
        //You could add a check though
        for(Account a : [Select ID, ParentID From Account Where ID IN :AllParents OR ParentID IN :AllParents]){

          if(!AllParents.contains(a.ID) || ( !AllParents.contains(a.parentID) && a.parentID != null)){

            if(a.parentID != null)
              AllParents.add(a.parentID);

            AllParents.add(a.id);
            //Reset flag to find more parents / children
            allDone = false;

          }
          
        }
        
      } while(allDone == false); 
     

 

There is an "idea" to disable jobs, but is there a way to mass delete them all using Apex?   Would like to delete the following:

 

Dashboard Refresh

Data Export

Scheduled Apex

Report Run

 

 

 

https://sites.secure.force.com/success/ideaView?id=08730000000HBnU

I have a table of date ranges split out by day and month, and I need to determine if a user provided date falls within the range. 
User-added image

I have no years in the table. I was using this logic:
if(qRec.Expected_Start_Date__c >= Date.newInstance(qRec.Expected_Start_Date__c.year(), Integer.valueOf(soqlResults.Start_Month__c), Integer.valueOf(soqlResults.Start_Day__c)) && 
                    qRec.Expected_Start_Date__c <= Date.newInstance(qRec.Expected_Start_Date__c.year(), Integer.valueOf(soqlResults.End_Month__c), Integer.valueOf(solqResults.End_Day__c))){
Which works for the majority of the use cases, until it crosses a year and needs to fall into the 12/25 - 1/24 range. I'd prefer to take year out of the comparison all together, as it is not relevant. Any suggestions appreciated. 
Thanks
 
I see that we can set Apex unit test with an annotation of @isTest(isParallel=true). That is awesome. However I'm requesting some clarification on its functionality.
  1. What is the default value? (I assume false... but don't like to assume)
  2. If I select a group of tests and indicate to SF that I want those tests to run in parallel, do I have to explicity set that to FALSE inorder to preform specific tests in serial? (or do they all run in parallel because I requested it)
  3. If I select a group of tests and indicate I want them run in serial, if isParallel set to TRUE does it over ride and still run in parallel?
Basically I want to understand the dynamics of isParallel before implementing in a LARGE project, that for years has run in serial. It has some tests that do NOT work in parallel, however we want to get the best possible performance out of the tests that can. So our HOPE is that we can tell Salesforce to run all tests in parallel, except the few that cannot, and run those in serial.  Is this the right feature to enable or set this.

Thanks in advance.

 

Simply put the following formula into a formula field of type "Text":

 

Id
& MID("ABCDEFGHIJKLMNOPQRSTUVWXYZ012345",(
    IF(FIND(MID(Id,1,1), "ABCDEFGHIJKLMNOPQRSTUVWXYZ")>0,1,0)
    +IF(FIND(MID(Id,2,1), "ABCDEFGHIJKLMNOPQRSTUVWXYZ")>0,2,0)
    +IF(FIND(MID(Id,3,1), "ABCDEFGHIJKLMNOPQRSTUVWXYZ")>0,4,0)
    +IF(FIND(MID(Id,4,1), "ABCDEFGHIJKLMNOPQRSTUVWXYZ")>0,8,0)
    +IF(FIND(MID(Id,5,1), "ABCDEFGHIJKLMNOPQRSTUVWXYZ")>0,16,0)
    )+1,1)
& MID("ABCDEFGHIJKLMNOPQRSTUVWXYZ012345",(
    IF(FIND(MID(Id,6,1), "ABCDEFGHIJKLMNOPQRSTUVWXYZ")>0,1,0)
    +IF(FIND(MID(Id,7,1), "ABCDEFGHIJKLMNOPQRSTUVWXYZ")>0,2,0)
    +IF(FIND(MID(Id,8,1), "ABCDEFGHIJKLMNOPQRSTUVWXYZ")>0,4,0)
    +IF(FIND(MID(Id,9,1), "ABCDEFGHIJKLMNOPQRSTUVWXYZ")>0,8,0)
    +IF(FIND(MID(Id,10,1), "ABCDEFGHIJKLMNOPQRSTUVWXYZ")>0,16,0)
    )+1,1)
& MID("ABCDEFGHIJKLMNOPQRSTUVWXYZ012345",(
    IF(FIND(MID(Id,11,1), "ABCDEFGHIJKLMNOPQRSTUVWXYZ")>0,1,0)
    +IF(FIND(MID(Id,12,1), "ABCDEFGHIJKLMNOPQRSTUVWXYZ")>0,2,0)
    +IF(FIND(MID(Id,13,1), "ABCDEFGHIJKLMNOPQRSTUVWXYZ")>0,4,0)
    +IF(FIND(MID(Id,14,1), "ABCDEFGHIJKLMNOPQRSTUVWXYZ")>0,8,0)
    +IF(FIND(MID(Id,15,1), "ABCDEFGHIJKLMNOPQRSTUVWXYZ")>0,16,0)
    )+1,1)

 

This is an optimized version of the code example "BPS: 18 digit external ID within the UI" you can find on the Online Help, but unlike the example provided there, it is small enough to fit into a formula field. Also, this code doesn't contain the error found in the online help example, where the second character byte equivalent of the first 5-character chunk was "4" instead of "2". I'd be more than happy if someone could come up with an even shorter version of this formula...Still, I hope you can use this.

 

Cheers,

Erik Mittmeyer