Apex Test Active Case Assignment Rules Assertion Fails

If you are testing active assignment rules you need to add it as an DMLOptions during testing else your assignment rule(s) will not get called and your assertion(s) may fail.

If you have one active Case Assignment Rule you can use dmlOpts.assignmentRuleHeader.useDefaultRule = true else you need to query for AssignmentRules. To query AssignmentRules you will need to have without sharing set as your class level access, else you will not get access to AssignmentRules.

If you have one method to insertCases you can make sure your assignmentRules run every time you execute a test class.

  public Id insertCase(Case bpCase){
      fflib_ISObjectUnitOfWork uow = Rest_App.UnitOfWork.newInstance();

      if (Test.isRunningTest()){
        Database.DMLOptions dmlOpts = new Database.DMLOptions();
         dmlOpts.assignmentRuleHeader.useDefaultRule = true;
         bpCase.SetOptions(dmlOpts);
      }

      uow.registerNew(bpCase);
      uow.commitWork();
      return bpCase.Id;
}

Here is the actual test class:

	@isTest(SeeAllData=true) static void testClientRequest(){
		RestRequest req = new RestRequest();
		RestResponse res = new RestResponse();
		Map<String, String> mapOfIds = App_Global_Test.setupCommunityUserReturnIds();

		test.startTest();
			System.runAs(new User(Id=mapOfIds.get('UserId'))){
				req.requestBody = Blob.valueOf('{"contactId":"'+mapOfIds.get('ContactId')+'", "type":"Client Request", "description":"Please help me with my account", "subject":"Client Request", "reason":"Client Request", "origin":"App"}');
				req.requestURI = '/v1/support/case';
				req.httpMethod = 'POST';
				RestContext.request = req;
				RestContext.response = res;

				App_Rest_Dispatcher.doPost();
				System.assert(res.responseBody!=null);
				System.assertEquals(res.statusCode, 200);
		 }
		test.stopTest();

		List<Case> supportCase = [Select Id, Subject, Description, Type, Owner.Name from Case where ContactId=:mapOfIds.get('ContactId')];
		System.assertEquals(supportCase.size(), 1);
		System.assertEquals(supportCase.get(0).Subject, 'Client Request');
		System.assertEquals(supportCase.get(0).Type, 'Client Request');
		System.assertEquals(supportCase.get(0).Owner.Name, 'Client Services Queue');
	}

Apex Run multiple batch jobs sequentially

We can run 3 batch jobs sequentially by incrementing the jobCounter and passing the integer (job index) into the batch scope

This can be increased to any amount of batch jobs, the problem I solved was able to update the Contact and disable Users in the same code running as different batch job.

As you cannot call @future in a batch method this solves by running each update in their own batch = transaction 👍🏻

global with sharing class App_Job_Account_Delete implements System.Schedulable, Database.Batchable<Integer>, Database.Stateful, Database.AllowsCallouts  {

    private List<JobError> jobErrors = new List<JobError>();

    global Integer jobCounter = 1;

    public void execute(SchedulableContext sc) {
        Database.executeBatch(this, jobCounter);
    }

    public Integer[] start(Database.BatchableContext context) {
        return new Integer[] {jobCounter};
    }

    public void execute(Database.BatchableContext context, Integer[] scope)     {
        try{
            if (isSandbox() || Test.IsRunningTest()){
                if(scope[0] == 1) {
                    //add your code here to run as part of 1st batch
                } else if (scope[0] == 2){
                    //add your code here to run as part of 2nd batch
                }  else if (scope[0] == 3){
                    //add your code here to run as part of 3rd batch
                }
            } else {
                JobError jobError = new JobError();
                jobError.message = 'Environment Error: Job will only run on dev and automation environment';
                jobError.records = new List<SObject>();
                jobErrors.add(jobError);
            }
        } catch (Exception ex){
            JobError jobError = new JobError();
            jobError.records = new List<SObject>();
            jobError.message = 'Exception: ' + ex.getTypeName() + ': ' + ex.getMessage()  + ' -- ' + ex.getCause();
            jobErrors.add(jobError);
        }
    }

    public void finish(Database.BatchableContext context){
        if (jobCounter<3){
            jobCounter++;
            Database.executeBatch(this, jobCounter);
        }
    }

    public class JobError{
        public String message;
        public List<SObject> records;
    }

    public void setJobError(List<JobError> jobErrors){
        this.jobErrors = jobErrors;
    }

    public static Boolean isSandbox() {
        if ([SELECT IsSandbox FROM Organization LIMIT 1].IsSandbox && ('Dev'.equalsIgnoreCase(CustomSettings.Environment__c) || 'Automation'.equalsIgnoreCase(CustomSettings.Environment__c))){
            return true;
        } else {
            return false;
        }
    }
}

Run the code as

Id batchprocessid = Database.executeBatch(new App_Job_Account_Delete());

Apex Comparator compare multiple object fields

Sorting a list of Analysis messages first by boolean and then integer. First we will order by condition and then order. All records where condition is true is will be on top in descending order on top followed by all false condition in descending order.

SummaryAnalysisMessages object to sort

public class SummaryAnalysisMessages {
		private String title;
		private String description;
		private Integer order;
		private Boolean condition;

		public SummaryAnalysisMessages(String title, String description, Integer order, Boolean condition){
			this.title = title;
			this.description = description;
			this.order = order;
			this.condition = condition;
		}

		public Boolean getCondition(){
			return condition;
		}

		public Integer getOrder(){
			return order;
		}
	}

Compare object by condition and then order

public class SummaryAnalysisMessagesCompare extends App_Comparator {
    public override Integer compare(Object a, Object b) {
			SummaryAnalysisMessages aSummaryMessage = (SummaryAnalysisMessages)a;
			SummaryAnalysisMessages bSummaryMessage = (SummaryAnalysisMessages)b;

      Integer summaryMessage1 = aSummaryMessage.getCondition() ? 1 : 0;
      Integer summaryMessage2 = bSummaryMessage.getCondition() ? 1 : 0;

			Integer compareInt = summaryMessage2 - summaryMessage1;
      if (compareInt == 0) {
          compareInt = aSummaryMessage.getOrder() - bSummaryMessage.getOrder();
      }
      return compareInt;
    }
}

Test class to test order

@isTest static void testSummaryAnalysisMessagesCompare(){
		SummaryAnalysisMessages summaryAnalysisMessage1 = new App_Chart.SummaryAnalysisMessages('1', '', 1, false);
		SummaryAnalysisMessages summaryAnalysisMessage2 = new App_Chart.SummaryAnalysisMessages('2', '', 2, true);
		SummaryAnalysisMessages summaryAnalysisMessage3 = new App_Chart.SummaryAnalysisMessages('3', '', 3, false);
		SummaryAnalysisMessages summaryAnalysisMessage4 = new App_Chart.SummaryAnalysisMessages('4', '', 4, true);

		List<SummaryAnalysisMessages> assetAllocationSummaryList = new List<SummaryAnalysisMessages>{summaryAnalysisMessage1, summaryAnalysisMessage2, summaryAnalysisMessage3, summaryAnalysisMessage4};

		App_Comparator.sort(assetAllocationSummaryList, new App_Chart.SummaryAnalysisMessagesCompare());
		System.assertEquals(assetAllocationSummaryList.get(0).getOrder(), 2);
		System.assertEquals(assetAllocationSummaryList.get(1).getOrder(), 4);
		System.assertEquals(assetAllocationSummaryList.get(2).getOrder(), 1);
		System.assertEquals(assetAllocationSummaryList.get(3).getOrder(), 3);
	}

Apex DocumentLink Trigger to Share Documents to Community Contacts

Trigger to check if the custom object has the correct file shared to community user

public without sharing class Domain_Documents extends fflib_SObjectDomain {

	public Domain_Documents(List<Documents__c> records) {
		super(records);
	}

	public class Constructor implements fflib_SObjectDomain.IConstructable{
		public fflib_SObjectDomain construct(List<SObject> sObjectList){
			return new Domain_Documents(sObjectList);
		}
	}

	public override void onAfterUpdate(Map<Id,SObject> existingRecords){
		List<ContentDocumentLink> contentDocumentLinksList = new List<ContentDocumentLink>();
		for (Documents__c documents : (List<Documents__c>) Records){
			if (documents.File_Id__c!=null){
				Documents__c existingDocument = (Documents__c)existingRecords.get(documents.Id);
				if (existingDocument.File_Id__c==null){
					List<ContentDocumentLink> contentDocumentLinkExists = [select ContentDocumentId, Id, IsDeleted, LinkedEntityId, ShareType, SystemModstamp, Visibility from ContentDocumentLink where ContentDocumentId=:documents.File_Id__c];
					Id userToShareWith = [Select Client__r.User__c from Documents__c where Id=:documents.Id].Client__r.User__c;
					Boolean flagToAddToDocs = true;
					for (ContentDocumentLink contentDocumentLinkExist : contentDocumentLinkExists){
						if (contentDocumentLinkExist.LinkedEntityId==userToShareWith){
							flagToAddToDocs=false;
						}
					}
					if (flagToAddToDocs){
						ContentDocumentLink cdl = new ContentDocumentLink(LinkedEntityId = userToShareWith , ContentDocumentId=documents.File_Id__c, shareType = 'C');
						contentDocumentLinksList.add(cdl);
					}
				 }
             }
		}

		if (!contentDocumentLinksList.isEmpty()){
			insert contentDocumentLinksList;
		}
	}
}

Test class to check that sharing is done correctly

@isTest(SeeAllData=true) static void testUpdate() {
		User communityUser = Global_Test.setupCommunityUserAndLogin();

		Documents__c bpDocument = (Documents__c)SmartFactory.createSObject('Documents__c');
		bpDocument.OwnerId = communityUser.Id;
		bpDocument.File_Name__c='Test';
		bpDocument.Document_Status__c = 'New';
		bpDocument.Client__c = communityUser.ContactId;
		insert bpDocument;

		String yourFiles = 'Some file content here';

		ContentVersion conVer = new ContentVersion();
		conVer.ContentLocation = 'S'; // S specify this document is in SF, use E for external files
		conVer.PathOnClient = 'test.txt'; // The files name, extension is very important here which will help the file in preview.
		conVer.Title = 'Test file '; // Display name of the files
		conVer.VersionData = EncodingUtil.base64Decode(yourFiles); // converting your binary string to Blog
		conVer.NetworkId=[Select Id from Network where Status='Live'][0].Id; //current Live community, should just be 1 but could have many
		insert conVer;

		Id conDoc = [SELECT ContentDocumentId FROM ContentVersion WHERE Id =:conVer.Id].ContentDocumentId; //query for contentDocumentId
	 	ContentDocumentLink cDe = new ContentDocumentLink();
		cDe.ContentDocumentId = conDoc;
		cDe.LinkedEntityId = bpDocument.Id; // you can use objectId,GroupId etc
		cDe.ShareType = 'C';
		cDe.Visibility = 'AllUsers';
		insert cDe;

		bpDocument.File_Id__c = conDoc;
		update bpDocument;

		Test.startTest();
			System.runAs(communityUser){
				bpDocument.File_Name__c='Update Name of File';
				update bpDocument;
			}
		Test.stopTest();

		Documents__c queryBpDocuments = [Select Id, File_Name__c, Document_Type__c from Documents__c where Id=:bpDocument.Id][0];
		System.assertEquals(queryBpDocuments.File_Name__c, 'Update Name of File');
	}

Apex generate a hash value for encrypting and decrypting emails

String cryptoSalt='249D5EC76175B12A';
Blob cryptoKey=Blob.valueof('J@NcRfUjXn2r5u8x/A?D(G-KaPdSgVkY');
Blob cryptoIv =Blob.valueof('4t6w9z$C&F)J@NcR');

Blob data = Blob.valueOf('youremail@gmail.com'+cryptoSalt);
Blob encryptedData = Crypto.encrypt('AES256', cryptoKey, cryptoIv, data);
String encodeDataHex = EncodingUtil.convertToHex(encryptedData);
System.debug('>>> encodeDataHex >>> ' + encodeDataHex);
//92939c472350e797aca42206a1b1d90f3b33bd1dbbac23af5fba40866515ef43e11e35edd354d341253bf89eb4094f2c

String encodeData = EncodingUtil.base64Encode(encryptedData);
System.debug('>>> encodeData >>> ' + encodeData);
//kpOcRyNQ55espCIGobHZDzszvR27rCOvX7pAhmUV70PhHjXt01TTQSU7+J60CU8s

// Decrypt the data - the first 16 bytes contain the initialization vector
Blob decodeData = EncodingUtil.base64Decode(encodeData);
Blob decryptedData = Crypto.decrypt('AES256', cryptoKey, cryptoIv, decodeData);

// Decode the decrypted data for subsequent use
String decryptedDataString = decryptedData.toString();
System.debug('>>> ' + decryptedDataString);
//youremail@gmail.com249D5EC76175B12A

Apex save class when scheduled > ‘This schedulable class has jobs pending or in progress’

How do I develop in a class that is referenced in a scheduled job?You will see the following error when you try to save this class:

This schedulable class has jobs pending or in progress

There is the workaround, what I did is create a Job scheduler so basically 1 scheduled class from where I reference all my scheduled classes. We are not initializing the class by creating a object of the class by name:

global class App_Job_Scheduler implements Schedulable {

	global void execute(SchedulableContext sc) {
		System.Type closedAccountsScheduler = Type.forName('Job_Closed_Accounts');
		Schedulable closedAccountObject = (Schedulable)closedAccountsScheduler.newInstance();
		closedAccountObject.execute(sc);
       }
}

Scheduler class, now you can schedule this class and will not get the >This schedulable class has jobs pending or in progress error when you try to save any code to App_Service or Selector_Financial_Account

global class Job_Closed_Accounts implements System.Schedulable, Database.Batchable<SObject>, Database.Stateful, Database.AllowsCallouts {

	global Database.QueryLocator start(Database.BatchableContext BC) {
		return App_Selector_Financial_Account.newInstance().selectAccountAndRelatedObjectsToDelete();
	}

    global void execute(Database.BatchableContext BC, List<Financial_Account__c> financialAccountIdsToBeDeleted) {
		List<Financial_Account__c> financialAccountsToDelete = App_Selector_Financial_Account.newInstance().selectAccountAndRelatedObjectsToDelete(financialAccountIdsToBeDeleted);
		App_Service.instance.deleteRelatedAccountsRecords(financialAccountsToDelete);
	}

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

Generating an Email-to-Case thread id using Apex

How to generate Email-to-Case thread id inside template:

Generate the thread Id

public static String getThreadId(String caseId){
public static String getThreadId(String caseId){
  return '[ ref:_'
     + UserInfo.getOrganizationId().left(5)
     + UserInfo.getOrganizationId().mid(11,4) + '._'
     + caseId.left(5)
     + caseId.mid(10,5) + ':ref ]';
}

Send customEmail and Add ThreadId

public void sendCustomEmail(User selectedUser, Contact selectedContact, String templateName, Map<String, String> customVariables){
    EmailTemplate emailTemplate = [select Id, Subject, HtmlValue, Body from EmailTemplate where DeveloperName=:templateName];

    if (selectedContact==null){
       selectedContact =  selectedUser.Contact;
    }

    String customSubject = emailTemplate.Subject;

    if (customVariables.containsKey('joinContactName')){
      customSubject = customSubject.replace('{!JointContactName}', customVariables.get('joinContactName'));
    }
    //Add ThreadId to the Subject
    if (customVariables.containsKey('ThreadId')) {
      customSubject = customSubject.replace('{!ThreadId}', customVariables.get('ThreadId'));
    }

    String htmlBody = emailTemplate.HtmlValue;
    htmlBody = htmlBody.replace('{!Contact.FirstName}',selectedContact.FirstName);
    htmlBody = htmlBody.replace('{!Contact.Email}', selectedContact.Email);
    if (customVariables.containsKey('Link')){
      htmlBody = htmlBody.replace('{!CustomUrl}', customVariables.get('Link'));
    } else if (customVariables.containsKey('link')){
      htmlBody = htmlBody.replace('{!CustomUrl}', customVariables.get('link'));
    } else if (customVariables.containsKey('joinContactName')){
      htmlBody = htmlBody.replace('{!JointContactName}', customVariables.get('joinContactName'));
    }

    //Add ThreadId to the htmlBody
    if (customVariables.containsKey('ThreadId')){
      htmlBody = htmlBody.replace('{!ThreadId}', customVariables.get('ThreadId'));
    }

    String plainBody = emailTemplate.Body;
    plainBody = plainBody.replace('{!Contact.FirstName}',selectedContact.FirstName);
    plainBody = plainBody.replace('{!Contact.Email}', selectedContact.Email);
    if (customVariables.containsKey('Link')){
      plainBody = plainBody.replace('{!CustomUrl}', customVariables.get('Link'));
    } else if (customVariables.containsKey('link')){
      plainBody = plainBody.replace('{!CustomUrl}', customVariables.get('link'));
    } else if (customVariables.containsKey('joinContactName')){
      plainBody = plainBody.replace('{!JointContactName}', customVariables.get('joinContactName'));
    }

    //Add the threadId to the plainBody
    if (customVariables.containsKey('ThreadId')){
      plainBody = plainBody.replace('{!ThreadId}', customVariables.get('ThreadId'));
    }

    Messaging.Singleemailmessage email = new Messaging.Singleemailmessage();
    List<OrgWideEmailAddress> orgWideEmailAddress = [Select Id, Address from OrgWideEmailAddress where DisplayName=:ORGWIDEEMAILADDRESSNAME];
    //Set ReplyTo as the Email-to-Case email address
    if (customVariables.containsKey('ThreadId')){
      List<EmailServicesAddress> emailServicesAddress = [SELECT Id,AuthorizedSenders,EmailDomainName,IsActive,LocalPart FROM EmailServicesAddress where IsActive=true and (LocalPart like '%service%' or LocalPart like '%support%')];
      if (!emailServicesAddress.isEmpty()){
        EmailServicesAddress emailToCase = emailServicesAddress.get(0);
        email.setReplyTo(emailToCase.LocalPart +'@'+ emailToCase.EmailDomainName);
        email.setSenderDisplayName('Client Support');
      } else {
        email.setReplyTo('customer-service@gmail.com');
        email.setSenderDisplayName('Client Support');
      }
    }

    email.setTargetObjectId(selectedContact.Id);
    email.setSaveAsActivity(true);

    email.setSubject(customSubject);

    email.setHtmlBody(htmlBody);
    email.setPlainTextBody(plainBody);

    if (customVariables.containsKey('WhatId')){
      email.setWhatId(customVariables.get('WhatId'));
    }

    Messaging.sendEmail(new Messaging.SingleEmailmessage[] {email});
}

Putting it all together

Map<String, String> mappingOfCaseFields = new Map<String, String>();
mappingOfCaseFields.put('ThreadId', App_Service.getThreadId(paymentCaseId));
App_Service.instance.sendCustomEmail(null, contact, 'App_Support_Template', mappingOfCaseFields);

Apex callout PATCH to Heroku Controller workaround

Setup a method to send Aync call to Heroku, add ‘?_HttpMethod=PATCH’ to the path to notify Heroku it’s a patch request

@future(callout=true)
	public static void callApiEndpointAsync(String apiEndpoint, String method, String aPayload){
		HttpRequest req = new HttpRequest();
		List<String> theArgs = new List<String>();
		HttpResponse res = new HttpResponse();
    try {
      if (apiEndpoint != null) {
        req.setTimeout(120000);
				if ('PATCH'.equals(method)){
					apiEndpoint += '?_HttpMethod=PATCH';
					req.setMethod('POST');
				} else {
					req.setMethod(method);
				}

        setAuthHeaderAsync(req);
        req.setEndpoint(herokuUrl + apiEndpoint);
				if (aPayload!=null)
					req.setBody(String.valueOf(aPayload));

				if (Test.isRunningTest() && (mock!=null)) {
					 mock.respond(req);
			 	} else {
					Integer retry = 0;

					while (retry < 2){
						Http http = new Http();
		        res =  http.send(req);
						if (res.getStatusCode() >= 200 && res.getStatusCode() < 300) {
							retry +=2;
						} else if (res.getStatusCode()==503 || res.getStatusCode()==400){
							retry +=1;
							res = http.send(req);
						} else {
							retry +=1;
							theArgs.add('Api');
							theArgs.add(req.getEndpoint());
							theArgs.add(res.getBody());
						}
					}
					throw new Rest_Exception(ResponseCodes_Mgr.getCode('HEROKU_REQUEST_CALLOUT_FAILED', null, theArgs));
				}

      } else {
        System.debug('Service apiEndpoint and payload must not be null');
        throw new Rest_Exception(ResponseCodes_Mgr.getCode('HEROKU_REQUEST_CALLOUT_FAILED'));
      }
    } catch (Exception ex) {
			theArgs.add('Api');
			theArgs.add(req.getEndpoint());
			theArgs.add(res.getBody());
			throw new Rest_Exception(ResponseCodes_Mgr.getCode('HEROKU_REQUEST_CALLOUT_FAILED', ex, theArgs));
			
    }
}

Spring controller checks the RequestParam _HttpMethod to see if it’s a POST or PATCH request

@RequestMapping(value = "/customer", method = RequestMethod.POST, produces = "application/json")
@ResponseBody
@ApiOperation(value = "Creates new payment customer")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Creates new payment customer")})
public String createCustomer(@RequestBody PaymentCustomerWrapper paymentCustomerWrapper, @RequestParam(value="_HttpMethod", defaultValue="POST")  String httpMethod)
        throws IOException, URISyntaxException {
     if (httpMethod!=null && "PATCH".equals(httpMethod)){
         itsLogger.debug("update payment customer {}", paymentCustomerWrapper.toString());
         return paymentService.updatePaymentCustomer(paymentCustomerWrapper).toJson();
    } else {
         itsLogger.debug("create payment customer {}", paymentCustomerWrapper.toString());
         return paymentService.createChargeBeeCustomer(paymentCustomerWrapper).toJson();
    }
}

Heroku deploy local jar to Maven Dependencies

Sometime a jar is not available via Maven Central Repository and you need to load a jar from your local filesystem. Copy the jar file to a lib directory in your project.

Execute the following command via command line

mvn deploy:deploy-file -Durl=file:salesforce/lib/ 
-Dfile=salesforce/lib/emp-connector-0.0.1-SNAPSHOT-phat.jar 
-DgroupId=com.salesforce.conduit 
-Dpackaging=jar 
-Dversion=0.0.1-SNAPSHOT 
-DartifactId=emp-connector

Add the following to maven pom.xml

 <repositories>
    <repository>
        <id>project.local</id>
        <name>project</name>
        <url>file:${project.basedir}/lib</url>
        <snapshots>
            <enabled>true</enabled>
        </snapshots>
    </repository>
 </repositories>
 <dependencies>
    <dependency>
        <groupId>com.salesforce.conduit</groupId>
        <artifactId>emp-connector</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
</dependencies>