Showing posts with label Salesforce. Show all posts
Showing posts with label Salesforce. Show all posts

Friday, April 1, 2016

Account Contact Roles on Contact layout

Salesforce has Contact Roles feature. Contact Role(s) could be applied for any Account and appear on Account layout as a related list. These Roles represent the role(s) that Contact(s) from the same or any other Account(s) plays in the Account. Such Roles could be also specified for Case, Contract, or Opportunity. When Contact roles defined, your team has more information to determine who to contact in particular circumstances.

Unfortunately Salesfroce does not provide any out-of-box tool to let User to see in which Account(s) the particular Contact involved. Means on Contact layout User can's see in which Account the Contact plays "Contact Role".

We want to share pretty easy solution to provide your Users such capability. Solution could be modified based on particular business requirements. Please do not hesitate to contact us if you want to leverage this solutions in your Salesforce instance.

STEP 1: Create VF page and APEX controller 

First you need to create custom Visualforce page which will display list of related to Contact Accounts and Contact Roles. Page's controller will consist of  SOQL SELECT related Account for current Contact. In our example we build Contact Roles for Account.

VF page:
ContactAccountsRolesDetails

<!-- 
Version      : 1.0
Company      : WebSolo Inc.
Date         : 03.2016
Description  : VF page "ContactAccountsRolesDetails" 
History      :             
-->
<apex:page standardController="Contact" extensions="ContactAccountsRolesDetailsContrExt" sidebar="false" showHeader="false" cache="false">
<style>
ul {
    margin-left: 0; 
    padding-left: 0;
}

li {
    list-style-type: none;
}    
</style>
    <apex:pageBlock >
        <apex:Messages />
        <apex:pageBlockTable value="{!listAccountContactRole}" var="acr" rendered="{!records}">
            <apex:column HeaderValue="Account Name">
                <!--<apex:outputText value="{!acr.Account.Name}"/>-->
                <a href="../{!acr.AccountId}" target="_parent"><apex:outputText value="{!acr.Account.Name}"/></a>
            </apex:column>
            <apex:column HeaderValue="Role">
                <apex:outputText value="{!acr.Role}"/>
            </apex:column>
            <apex:column HeaderValue="Primary">
                <apex:outputField value="{!acr.IsPrimary}"/>
            </apex:column>
        </apex:pageBlockTable>
        
    </apex:pageBlock>
</apex:page>


Controller:
ContactAccountsRolesDetailsContrExt


/*
    Version        : 1.0
    Company        : Websolo inc. 
    Date           : 03/2016
    Description    : 
    Update History : 
*/
public class ContactAccountsRolesDetailsContrExt
{ 
    public Id idContact;
    public Boolean records {get; set;}
    public List listAccountContactRole {get; set;}
    
    public ContactAccountsRolesDetailsContrExt(ApexPages.StandardController Controller) 
    {
        records = false;
        idContact = Controller.getRecord().id;
        listAccountContactRole = [SELECT id, AccountId, Account.Name, ContactId, Role, IsPrimary FROM AccountContactRole WHERE ContactId =: idContact];
        
        if (listAccountContactRole.size() != 0)
        {
            records = true;
        }
        else
        {
            Apexpages.Message noRecords = new Apexpages.Message(ApexPages.severity.INFO, 'No records to display');
            Apexpages.addMessage(noRecords);
        }
    }
}

STEP 2: Add VF page to layout

When created VF page could be added to Contact Layout as in example below.






Friday, March 4, 2016

Disable and animate APEX command button after click to avoid double submission


There is wide known scenario when click to APEX command button on custom VF page would take quite long time to perform calculation on server side and return the result back to UI. User may try to click the button again which will result in unexpected and undesired consequences. Especially if click to the button invokes DML operations.

There are a few workarounds to avoid such scenarios. In this post you will the most popular workarounds with analysis about their PROS and CONS.

Solution could be modified based on particular business requirements. Please do not hesitate to contact us if you want to leverage any of this solutions in your Salesforce instance.

Notes related to all examples below:

  • As a $Resource.statusbar you can use any .gif animated "in progress" image
  • In all demos we used external controller to build mathematic curves to simulate server activity

#1 Disabling of APEX command button using jQuery. Replacing button with animated GIF

Disabling the button once the user clicks the button could be the straight forward solution. In this solution we will replace the button once the user clicks the button using jQuery

VF page:
DisableApexCommandBut
ton to demo disable Button
<!-- 
Version      : 1.0
Company      : WebSolo Inc.
Date         : 03.2016
Description  : VF page "DisableApexCommandButton" to demo disable Button
History      :             
-->

<apex:page sidebar="false" showheader="false" cache="false" expires="0" controller="DisableApexCommandButtonContr">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <apex:composition template="{!$Site.Template}">
    <apex:define name="body">
    <apex:form style="width:550px;" id="f1">
        <apex:outputPanel >
            <apex:commandButton style="margin-top:20px;margin-left:250px;margin-bottom:25px;height:30px;font-size:12px" styleClass="b1" value="Generate" status="status" action="{!run}" rerender="f1"/>
            <div style="display: none;   margin-left: 250px;"  class="statusbardiv">
                <apex:image width="70px" url="{!$Resource.statusbar}" />
            </div>
            <apex:selectRadio value="{!chart}">
                <apex:selectOptions value="{!items}"/>
            </apex:selectRadio><p/>
            <apex:actionStatus id="status" onstart="$('.statusbardiv').css('display','block');$('.b1').css('display','none');" onstop="$('.statusbardiv').css('display','none');$('.b1').css('display','block');" />    
            <div>
                <apex:chart height="300" width="500" data="{!data}">
                    <apex:legend position="top"/>
                    <apex:axis title="Y" type="Numeric" position="left" grid="true" fields="valY"/>
                    <apex:axis title="X" type="Numeric" position="bottom" fields="valX" />
                    <apex:lineSeries title="{!chart}" axis="left" xField="valX" yField="valY"/>
                </apex:chart>
            </div>  
        </apex:outputPanel>
    </apex:form>
    </apex:define>
    </apex:composition>
</apex:page>

PROS: Easy to implement. Looks good.
CONS:  Requires jQuery library.

#2 Call custom div as an overhead "modal window"

Another solution would be not try to "disable" buttons, but to call custom modal window which will prevent user from multiple clicks and multiple form submission.

VF page: DisableApexCommandButton
<!--
    Version        : 1.0
    Company        : Websolo inc. 
    Date           : 03/2015
    Description    : Call custom div as an overhead "modal window"
    Update History : 
-->
<apex:page sidebar="false" showheader="false" cache="false" expires="0" controller="DisableApexCommandButtonContr">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <style>
    .disabledbutton {
        pointer-events: none;
        opacity: 0.4;
        background-color:#E1E1E1;
    }
    </style>
    <apex:composition template="{!$Site.Template}">
    <apex:define name="body">
    <apex:form style="width:550px;" id="f1">
        <apex:actionStatus id="status" onstart="$('#mydiv').addClass('disabledbutton');$('.statusbardiv').css('display','block');" onstop="$('#mydiv').removeclass('disabledbutton');$('.statusbardiv').css('display','none');" />
        <div style="display: none; position: fixed; z-index: 999; margin-left: 250px; margin-top: 200px"  class="statusbardiv">
            <apex:image width="70px" url="{!$Resource.statusbar2}" />
        </div>
        <div id="mydiv">
            <apex:outputPanel >
                <apex:commandButton style="margin-top:20px;margin-left:250px;margin-bottom:25px;height:30px;font-size:12px" styleClass="b1" value="Generate" status="status" action="{!run}" rerender="f1"/>
                <apex:selectRadio value="{!chart}">
                    <apex:selectOptions value="{!items}"/>
                </apex:selectRadio><p/>    
                <div>
                    <apex:chart height="300" width="500" data="{!data}">
                        <apex:legend position="top"/>
                        <apex:axis title="Y" type="Numeric" position="left" grid="true" fields="valY"/>
                        <apex:axis title="X" type="Numeric" position="bottom" fields="valX" />
                        <apex:lineSeries title="{!chart}" axis="left" xField="valX" yField="valY"/>
                    </apex:chart>
                </div>  
            </apex:outputPanel>
        </div>
    </apex:form>
    </apex:define>
    </apex:composition>
</apex:page>

PROS: Works better in some cases
CONS: Not visually perfect for some users who not used to such approach. Also requires jQuery library.

#3 Disabling of APEX command button using apex:facet method

In this solution we will replace the button with "Processing..." text once the user clicks the button

VF page:
DisableApexCommandButton
<!--
    Version        : 1.0
    Company        : Websolo inc. 
    Date           : 03/2015
    Description    : Disabling of APEX command button using apex:facet method
    Update History : 
-->
<apex:page sidebar="false" showheader="false" cache="false" expires="0" controller="DisableApexCommandButtonContr">

    <apex:composition template="{!$Site.Template}">
    <apex:define name="body">
    <apex:form style="width:550px;" id="f1">
        <apex:outputPanel >
            <apex:actionStatus id="status">
            <apex:facet name="stop">
                <apex:commandButton style="margin-top:20px;margin-left:250px;margin-bottom:25px;height:30px;font-size:12px;width:90px" action="{!run}" status="status" value="Generate" disabled="false" rerender="f1"/>
            </apex:facet> 
            <apex:facet name="start">
                <apex:commandButton style="margin-top:20px;margin-left:250px;margin-bottom:25px;height:30px;font-size:12px;width:90px" action="{!run}" status="status" value="Processing..." disabled="true"/>
            </apex:facet>
            </apex:actionStatus>
            <apex:selectRadio value="{!chart}">
                <apex:selectOptions value="{!items}"/>
            </apex:selectRadio><p/>
            <div>
                <apex:chart height="300" width="500" data="{!data}">
                    <apex:legend position="top"/>
                    <apex:axis title="Y" type="Numeric" position="left" grid="true" fields="valY"/>
                    <apex:axis title="X" type="Numeric" position="bottom" fields="valX" />
                    <apex:lineSeries title="{!chart}" axis="left" xField="valX" yField="valY"/>
                </apex:chart>
            </div>  
        </apex:outputPanel>
    </apex:form>
    </apex:define>
    </apex:composition>
</apex:page>

PROS: Efficient and user friendly
CONS: None

Sunday, December 27, 2015

Self recurring class to create test records in Salesforse object

While working on Round Robin Incidents Assignment Routine for BMC Remedyforce we've built a tool to auto create test Incident records. This tool creates new record every one minute simulating real environment.

After minor modifications the same solution could be used for similar purposes to simulate creating records in standard or custom from SFDC UI. Below we provided example of self recurring class to create test Contact records.

The code has comments however please feel free to Contact Us if you have any questions.

APEX Class: AutoContactsCreator
/*
Version      : 1.0
Company      : WebSolo inc.
Date         : 12.2015
Description  : APEX class to automatically create new test Contact record (with some test data) each 5 minutes
History      :             
*/
global class AutoContactsCreator implements Schedulable{
 //Execute method
    global void execute(SchedulableContext SC) {
        //Code to check if test Account with name 'Test Account' exists and to create one if not.
        List acc = [SELECT id FROM Account WHERE Name = 'Test Account' limit 1];
        if(acc.size() == 0){
            Account NewAcc = new Account();
            NewAcc.Name = 'Test Account';
            insert NewAcc;
            acc.add(NewAcc);
        }
        //Code to check if test Contacts (created before with name AutoContact) exist and to identify the most recent Name (to auto increase name for new one).
        Contact con = new Contact();
        con.AccountId = acc[0].id;
        //Get next number of autocontact
            //Get last AutoContact record and parce LastName value
             List lastCon = [SELECT Name FROM Contact WHERE LastName LIKE 'AutoContact%' ORDER BY CreatedDate DESC LIMIT 1];
             //If exist, substring most recent name OR start form 1
             Integer NumOfNextAutoCon;
             if(lastCon.size() != 0){
                 String nameOfLastAutoCon = lastCon[0].Name;
                 NumOfNextAutoCon = Integer.valueOf(nameOfLastAutoCon.substringAfter('AutoContact')) + 1;
             }
             else{
                NumOfNextAutoCon = 1;
             }
        //Prepare values for First/Last Name, Phone, Email     
        con.FirstName = 'Test';
        con.LastName = 'AutoContact' + NumOfNextAutoCon;
            //Generate random number for phone from 1000000 to 9999999
            Integer uniqueVal =  Math.round(Math.random()*1000000) + 999999 ;
        con.Phone = '416' + uniqueVal;
        con.Email = 'AutoContact' + NumOfNextAutoCon + '@TestAccount.com';
        insert con;
        
        //This code section will schedule next class execution in 5 minutes from now
        datetime nextScheduleTime = system.now().addMinutes(1);
        string minute = string.valueof(nextScheduleTime.minute());
        string second = string.valueof(nextScheduleTime.second ());
        string cronvalue = second+' '+minute+' * * * ?';
        string jobName = 'AutoContactsCreator ' + nextScheduleTime.format('hh:mm');
        AutoContactsCreator p = new AutoContactsCreator();
        system.schedule(jobName, cronvalue , p);
 
        //This code section to be used to abort auto-scheduled job
        system.abortJob(sc.getTriggerId());
    }
    //Method to start shedule job form console
    public void startJob(){
        datetime nextScheduleTime = system.now().addMinutes(1);
        string minute = string.valueof(nextScheduleTime.minute());
        string second = string.valueof(nextScheduleTime.second ());
        string cronvalue = second+' '+minute+' * * * ?' ;
        string jobName = 'AutoContactsCreator ' + nextScheduleTime.format('hh:mm');   
        AutoContactsCreator p = new AutoContactsCreator();
        system.schedule(jobName, cronvalue , p);    
    }
    //Method to abort shedule job (with 'AutoContactsCreator' name) form console
    public void deleteJob(){
        CronTrigger job = [SELECT Id, CronJobDetail.Id, CronJobDetail.Name, CronJobDetail.JobType FROM CronTrigger where CronJobDetail.Name LIKE 'AutoContactsCreator%'];
        system.abortJob(job.Id);
    }
 }

APEX Class: AutoContactsCreator_TESTclass
/*
Version      : 1.0
Company      : WebSolo inc.
Date         : 12.2015
Description  : APEX test coverage class for AutoContactsCreator class
History      :             
*/
@isTest
private class AutoContactsCreator_TESTclass {
    static testMethod void myUnitTest() {
        AutoContactsCreator autoCrCon = new AutoContactsCreator();
        autoCrCon.StartJob();
        autoCrCon.deleteJob();
        system.schedule('Test', '0 0 * * * ?' , autoCrCon);
    } 
}

SFDC Developer Console commands to use with AutoContactsCreator class

To execute self recurring class
AutoContactsCreator autoCrCon = new AutoContactsCreator();
autoCrCon.StartJob();

To abort self recurring class
AutoContactsCreator autoCrCon = new AutoContactsCreator();
autoCrCon.deleteJob();
Note: You also can abort the job manually here Setup -> Jobs -> Scheduled Jobs

Helpful command to DELETE all previously created by self recurring class test records
DELETE [SELECT id FROM Contact WHERE LastName LIKE 'AutoContact%'];

Monday, June 8, 2015

Custom Salesforce Round Robin Incidents Assignment Routine for BMC Remedyforce

Salesforce Round Robin Assignment Routine for BMC Remedyforce was built for companies wanting to automatically distribute and assign incoming Incidents to the Members of different Support Teams (Groups) depending on Incident creation time and Group's Time Zone.

We have multiple Assignment Routine implementations for different businesses who use BMC Remedyforce and Salesfroce. Armed with multiple extra features Round Robin Incidents Assignment Routine for BMC Remedyforce works extremely well and deserved great references.

For instance please take a look at this reference - shared by our client who we recently helped with the RemedyForce Round Robin customization:
https://communities.bmc.com/ideas/3675#comment-62436

Please do not hesitate to Contact Us if you have any questions or wish to add this extremely useful functionality to your Salesforce with Remedyforce instance. We'll happy to reply with answers, licensing options and pricing details.


Round Robin for BMC Remedyforce
Most important Functional Features:

- "Assignment Groups" Tab (Console) to manage multiple Groups of Users involved in "Round Robin" assignment routine and monitor their current indicators such as Time Zone, Assignment Score, Status, etc.
- Capability to enable/disable particular Group(s) from round robin cycle
- Capability to assign Members to Groups based on Shifts ("Assignment Time Frame" feature)
- Capability to activate/deactivate Group's Members from round robin cycle if the Member is sick or on vacation
- Potential capability for Members to "check out/check in" from/to round robin cycle ("Self Management" feature)
- Capability to set Share for each Member in the Group - as a % of the total records received from assignment Queue during the day ("Not Equal Share" feature)
- Reporting capabilities to help manager to track Round Robin Assignment statistics

Other Details:
- 100% Native SFDC Application. Means no servers or outside services required.
- Supports following Salesforce.com Editions: Enterprise, Unlimited, Developer
- Instant processing time, no assignment delays

Solution functionality could be amended and enhanced to meet additional particular business requirements. Here are few possible scenarios:
- "Day time" Group(s) to handle the normal working day Incidents and "on call" Group for off-hours support
- Assign Incidents to Group(s) designated to particular Incident Priority/Impact or any other set of custom criteria
- Auto login/logout Members from/to Round Robin cycle based on their login and log out time in Salesforce. So that they wouldn't receive Incidents if they are not actually working now.

Screens
1) Assignment Groups ConsoleAssignment Groups Console

2) Assignment Group layout
Assignment Group layout

 3) Group Member layout
Group Member layout

Thursday, May 14, 2015

Let your Contacts update their Email preferences using Force.com Site without authentication. Configuring the public Force.com Site.

Force.com Sites is relatively known feature which allows SFDC developers to set up public-facing sites/pages hosted by Salesforce platform. Using Force.com Site you can build micro web sites with one landing page or complicated sites with multiple pages. Such sites could have complicated flows to expose/collect information from/to Salesfroce. Advanced Force.com sites could even (for instance) accept credit card payments.

In this post we will show how to built quite easy but useful Force.com site and page with a purpose to let your Salesforce Contacts update their Email preferences themself, without contacting your support team. I.e. unsubscribe by updating Email Opt Out checkbox in related Salesforce record.

Solution could be modified based on particular business requirements.
Please do not hesitate to contact us if you want to leverage this solutions in your Saleforce instance.

Here's how the solution flow works:
  1. SFDC (or mass mail application) sends marketing emails out to customers (SFDC Contacts).
  2. Email will consist of "manage my subscription" or "unsubscribe" link. The link will be unique for each Contact and consist of "encrypted" Contact's ID. Encrypting is recommended to hide real SFDC Contatc ID (15-character) for security reasons. See the link with “hash id” (in yellow) below as an example.
  3. End user clicks on that URL and opens a Force.com site page, change his Email preferences and click "Update"to commit updates to SFDC.
Unique URL in email for end customer will looks like this:
http://yourdomain.force.com/emailpreferences/profile/fd90b5cd3bda11119f79a0c8131ab2ac7266d3f54add67f276c396e74f906da4

Step 0: Create new trigger to populate HashId field on Contact object

As mentioned above we suggest to encrypt native SFDC ID to improve your Force.com site security.
This technique allows to hide and not publicly expose your SFDC Contact record's ID. Instead of this Force.com site will use Crypto generated (algorithm SHA256) compact representations of the original ID value which will be "decrypted" back by URL rewriter controller class (see below).

First please create new HashId [HashId__c, Text (255)] field on Contact object. To make the field indexed by SFDC (and improve Force.com site response time) set External ID check box to TRUE.
Then create ContactHashId trigger to populate the field with encrypted value. 

NOTE: Trigger fires on "after insert", "before update" events on Contact object. Please make sure you will "update" existing Contacts using APEX scheduled Job or DataLoader.


APEX trigger: ContactHashId
/*
Version      : 1.0
Company      : WebSolo inc.
Date         : 05.2015
Description  : trigger to populate the HashId field on Contact object (used by PublicEmailPreferencesURLRewriter class)
History      :             
*/

trigger ContactHashId on Contact (after insert, before update) {

    // Generate hash ids for all contacts that don't have them.
    List<Contact> contactsToUpdate = new List<Contact>();
    for (Contact c : Trigger.new) {
        if (c.HashId__c == null) {
            String hashId = EncodingUtil.convertToHex(Crypto.generateDigest('SHA-256', Blob.valueOf((String)c.Id)));
            if (Trigger.isInsert) {
                contactsToUpdate.add(new Contact(Id = c.Id, HashId__c = hashId));
            } else {
                c.HashId__c = hashId;
            }
        }
    }
    if (!contactsToUpdate.isEmpty()) {
        update contactsToUpdate;
    }
}

Step 1: Set up Unique Domain Name for your SFDC instance

You can set up your Force.com Site by going to Setup | Develop | Sites

If your company does not have Force.com Site yet, you will be able to register a Force.com domain name that you like (upon availability).

NOTE: Be careful when registering the domain name on your Production instance. After registration you will not be able to change it! As per Salesforce "You cannot modify your Force.com domain name after the registration process."

Step 2: Create Force.com site components (VF page, APEX controllers, template) 

Create and save following Force.com site components.

VF page (Active Site Home Page): PublicEmailPreferences
<!-- 
Version      : 1.0
Company      : WebSolo Inc.
Date         : 05.2015
Description  : VF page "PublicEmailPreferences" to serve as a page in Force.com site
History      :             
-->

<apex:page controller="PublicEmailPreferencesController" cache="false" expires="0" showHeader="false" sidebar="false">

<style>
body { font-size: 100%; }
.contactInfo { margin: 20px 0px; }
.contentPanel { float: left; margin: 5px 0px 20px 20px; }
.contactLabel { float: left; font-weight: bold; width: 10em; }
h1 { color: #cc6611; font-size: 200%; padding-top: 25px;}
input[type="checkbox"] { height: 20px; width: 20px; }
.detailPanel { float: left; margin-left: 10px; width: 16em;margin-top:10px }
.logo { margin: 0px 100px 0px 20px; width: 250px; }
.selectionLabelPanel { float: left; margin-bottom: 10px; }
.selectionLabel { font-weight: bold; }
.selectionCheckboxPanel { float: right; }
</style>

<apex:composition template="{!$Site.Template}">
<apex:define name="logo">
<!-- 
You can add the logo here as a link to static resource 
<apex:image styleClass="logo" value="{!$Resource.LOGO_RESOURCE_NAME}" />
-->
</apex:define>

<apex:define name="headline">
  <h1>Email Opt Out Preferences</h1>
</apex:define>

<apex:define name="body">

  <apex:form >
  <apex:outputPanel id="leftPanel" layout="block" rendered="{!showPrefs}" styleClass="contentPanel" >    
    <apex:outputPanel layout="block" >
      <apex:outputText value="Keep your email preferences up to date." />
    </apex:outputPanel>    
    <apex:outputPanel layout="block" styleClass="contactInfo" >
      <apex:outputPanel layout="block" styleClass="contactLabel" >
        <apex:outputText value="Email" />
      </apex:outputPanel>
      <apex:outputPanel layout="block" >
        <apex:outputText value="{!contact.Email}" />
      </apex:outputPanel>
      <apex:outputPanel layout="block" styleClass="clearBoth" />
    </apex:outputPanel>    
    <apex:outputPanel layout="block" styleClass="contactInfo" >
      <apex:outputPanel layout="block" styleClass="contactLabel" >
        <apex:outputText value="First Name" />
      </apex:outputPanel>
      <apex:outputPanel layout="block" >
        <apex:outputText value="{!contact.FirstName}" />
      </apex:outputPanel>
      <apex:outputPanel layout="block" styleClass="clearBoth" />
    </apex:outputPanel>    
    <apex:outputPanel layout="block" styleClass="contactInfo" >
      <apex:outputPanel layout="block" styleClass="contactLabel" >
        <apex:outputText value="Last Name" />
      </apex:outputPanel>
      <apex:outputPanel layout="block" >
        <apex:outputText value="{!contact.LastName}" />
      </apex:outputPanel>
      <apex:outputPanel layout="block" styleClass="clearBoth" />
    </apex:outputPanel>    
    <apex:outputPanel layout="block" styleClass="contactInfo" >
      <apex:outputPanel layout="block" styleClass="clearBoth" />
    </apex:outputPanel>    
    <apex:outputPanel layout="block" >
      <apex:outputText value="To request an update to your profile information, please kindly contact our " />
      <apex:outputLink target="_top" style="color:#cc6611" value="mailto:SUPPORT%40YOURCOMAPNYDOMAIN.com?subject=Please%20update%20my%20information">support team</apex:outputLink>
      <apex:outputText value="." />
    </apex:outputPanel>    
  </apex:outputPanel>
  
  <apex:outputPanel layout="block" styleClass="clearBoth" />
  
  <apex:outputPanel id="rightPanel" layout="block" rendered="{!showPrefs}" styleClass="contentPanel" >    
    <apex:outputPanel layout="block" >
      <apex:outputText value="Select the checkbox if you do not want to receive emaild form us." />     
    </apex:outputPanel>
    <apex:outputPanel layout="block" styleClass="detailPanel" >    
      <apex:outputPanel layout="block" styleClass="selectionPanel" >
        <apex:outputPanel layout="block" styleClass="selectionLabelPanel" >
          <apex:outputText styleClass="selectionLabel" value="Opt Out Of Emails" />
        </apex:outputPanel>
        <apex:outputPanel layout="block" styleClass="selectionCheckboxPanel" >
          <apex:inputCheckbox styleClass="selectionCheckbox" value="{!subEmailOptOut}" />
        </apex:outputPanel>
      </apex:outputPanel>        
    </apex:outputPanel>
    <apex:outputPanel layout="block" styleClass="clearBoth" />
    <apex:outputPanel id="buttonPanel" layout="block" >
      <apex:actionStatus id="saveStatus">
        <apex:facet name="start">
            <apex:outputPanel >
            Updating...&nbsp;<img src="{!$Resource.AnimatedBusy}" />
          </apex:outputPanel>
        </apex:facet>
        <apex:facet name="stop">
          <apex:commandButton action="{!updatePreferences}" rerender="messagesPanel" status="saveStatus" style="background: #cc6611; color: white; font-size: 200%; margin-top: 20px;" styleClass="updateBtn" value="Update" />
        </apex:facet>
      </apex:actionStatus>
    </apex:outputPanel>    
  </apex:outputPanel>

  <apex:outputPanel layout="block" styleClass="clearBoth" />

  <apex:outputPanel id="messagesPanel" layout="block" style="max-width: 400px;" >
    <apex:outputPanel layout="block" rendered="{!hasMessages}" style="{!messagePanelStyle}" >
      <apex:repeat value="{!messages}" var="message">
        <apex:outputText value="{!message}" />
      </apex:repeat>
    </apex:outputPanel>
  </apex:outputPanel>

  </apex:form>

</apex:define>

</apex:composition>

</apex:page>

NOTE: For $Resource.AnimatedBusy please use any animated GIF illustrate "progress"

VF page controller (for Active Site Home Page): PublicEmailPreferencesController
/*
Version        : 1.0
Company        : WebSolo Inc.
Date           : 05.2015
Description    : controller for PublicEmailPreferences VF page 
Update History :

*/ 

public without sharing class PublicEmailPreferencesController {

    public Contact contact { public get; private set; }
    public Boolean subEmailOptOut { public get; public set; }
    public String rsaEmail { public get; private set; }
    public String rsrEmail { public get; private set; }
    public List<String> messages { public get; private set; }
    public Boolean hasMessages { public get {return messages != null && !messages.isEmpty();} private set; }
    public String messagePanelStyle { public get {return hasErrorMessage ? ERROR_STYLE : INFO_STYLE;} private set; }
    public Boolean showPrefs { public get; private set; }
    
    private Boolean hasErrorMessage = false;
    
    public final static String URL_PARM_ID = 'id';
    public final static String INFO_STYLE = 'color: green; background-color: #efe; padding: 10px; margin: 10px; border: 1px solid green;';
    public final static String ERROR_STYLE = 'color: red; background-color: #fee; padding: 10px; margin: 10px; border: 1px solid red;';
    public final static String ERR_CONTACT_NOT_FOUND = 'We are unable to retrieve your information at this time.';
    public final static String ERR_PREFS_UPDATE_FAILED = 'We are unable to update your preferences at this time.';
    public final static String ERR_PREFS_UPDATE_SUCCEEDED = 'Your preferences have been updated.';
    
    public PublicEmailPreferencesController() {
        
        clearMessages();
        
        String contactId = ApexPages.currentPage().getParameters().get(URL_PARM_ID);
        System.debug('id=' + contactId);
        if (contactId != null) {
            try {
                contact = getContactForId(contactId);
                if (contact != null) {
                    subEmailOptOut = contact.HasOptedOutOfEmail;
                    showPrefs = true;
                }
            } catch (Exception e) {
                addErrorMessage(ERR_CONTACT_NOT_FOUND);
            }
        } else {
            addErrorMessage(ERR_CONTACT_NOT_FOUND);
        }
    }
    
    private void addErrorMessage(String message) {
        if (messages == null) messages = new List<String>();
        messages.add(message);
        hasErrorMessage = true;
    }
    
    private void addInfoMessage(String message) {
        if (messages == null) messages = new List<String>();
        messages.add(message);
    }
    
    private void clearMessages() {
        if (messages == null) messages = new List<String>();
        messages.clear();
        hasErrorMessage = false;
    }
    
    private Contact getContactForId(String contactId) {
        Contact contact = null;
        List<Contact> contacts = [SELECT HasOptedOutOfEmail, Email, FirstName, Id, LastName FROM Contact WHERE Id = :contactId];
        if (contacts.size() == 1) {
            contact = contacts[0];
            
        } else {
            addErrorMessage(ERR_CONTACT_NOT_FOUND);
        }
        return contact;
    }
    
    public PageReference updatePreferences() {
        try {
            clearMessages();
            contact.HasOptedOutOfEmail = subEmailOptOut;
            update contact;
            addInfoMessage(ERR_PREFS_UPDATE_SUCCEEDED);
        } catch (Exception e) {
            addErrorMessage(ERR_PREFS_UPDATE_FAILED);
        }
        return null;
    }
}


VF page (template for site VF pages): PublicSiteTemplate
<!-- 
Version      : 1.0
Company      : WebSolo Inc.
Date         : 05.2015
Description  : VF page "PublicSiteTemplate" to serve as a Force.com Site Template
History      :             
-->
<apex:page showHeader="false" sidebar="false" id="PublicSiteTemplate" cache="false" expires="0" >
    <head>
        <title>FPC</title>
        
        <style>
            #fullContainer { }
            #headerContainer { padding: 0px 10px; }
            #logoContainer { float: left; }
            #contentContainer { padding-left: 10px; }
            #headlineContainer { float: left; margin-top:10px}
            #footerContainer { padding-left: 10px; }
            #footerbar { background-color: #cc6611; line-height: 0.5em; max-width: 650px; }
            .clearBoth { clear: both; }
        </style>
    </head>
    <body>
        <div id="fullContainer">
            <div id="headerContainer">
                <div id="logoContainer">
                    <apex:insert name="logo"/>
                </div>
                <div id="headlineContainer">
                    <apex:insert name="headline"/>
                </div>
                <div class="clearBoth"></div>
            </div>
            <div id="contentContainer">
                <div id="mainContent">
                    <apex:insert name="body"/>
                </div>
                <div class="clearBoth"></div>
            </div>
            <div id="footerContainer">
                <div id="footerLinks"></div>
                <div class="clearBoth"></div>
                <div id="footerbar">&nbsp;</div>
                <div class="clearBoth"></div>
            </div>
        </div>
    </body>
</apex:page>


APEX class (URL rewriter): PublicEmailPreferencesURLRewriter
/*
Version      : 1.0
Company      : WebSolo inc.
Date         : 05.2015
Description  : controller to support URL Rewrite for Force.com VF page "PublicEmailPreferences"
History      :             
*/

global class PublicEmailPreferencesURLRewriter implements Site.UrlRewriter {
    public static final String EMAIL_PROFILE_FRIENDLY = '/profile/';
    public static final String EMAIL_PROFILE_VF_PAGE_BASE = '/PublicEmailPreferences';
    public static final String EMAIL_PROFILE_VF_PAGE = EMAIL_PROFILE_VF_PAGE_BASE + '?' + PublicEmailPreferencesController.URL_PARM_ID + '=';

    global PageReference[] generateUrlFor(PageReference[] urls) {
        
        System.debug('generateUrlFor has been invoked for ' + urls);
        PageReference[] pageRefs = new List<PageReference>();
        
        Set<Id> cIds = new Set<Id>();
        for (PageReference pRef : urls) {
            String urlStr = pRef.getUrl();
            if (urlStr.startsWith(EMAIL_PROFILE_VF_PAGE_BASE)) {
                cIds.add(urlStr.substring(EMAIL_PROFILE_VF_PAGE.length()));
            }
        }
        
        Map<Id, Contact> contactsById = new Map<Id, Contact>([SELECT Id, HashId__c FROM Contact WHERE Id IN :cIds]);
        for (PageReference pRef : urls) {
            String urlStr = pRef.getUrl();
            pageRefs.add(
                urlStr.startsWith(EMAIL_PROFILE_VF_PAGE_BASE) ?
                new PageReference(EMAIL_PROFILE_FRIENDLY + contactsById.get(urlStr.substring(EMAIL_PROFILE_VF_PAGE.length())).HashId__c) :
                pRef
            );
        }
         return pageRefs;
    }
    
    global PageReference mapRequestUrl(PageReference url) {
        
        PageReference pageRef = null;
        
        String urlStr = url.getUrl();
        System.debug('mapping url=' + urlStr);
        
        if (urlStr.startsWith(EMAIL_PROFILE_FRIENDLY)) {
            String hashId = urlStr.substring(EMAIL_PROFILE_FRIENDLY.length());
            if (hashId != '') {
                List<Contact> contacts = [SELECT Id FROM Contact WHERE HashId__c = :hashId];
                if (!contacts.isEmpty()) {
                    pageRef = new PageReference(EMAIL_PROFILE_VF_PAGE + contacts[0].Id);
                } else {
                    pageRef = new PageReference(EMAIL_PROFILE_VF_PAGE);
                }
            }
        }
        return pageRef; 
    }
}


Step 3: Configuring new Force.com Public Site

Press the "New" button to create a new Force.com Site and enter the following values – you can leave all the other fields as-is. Click Save when done.
    • Site Label – name (may contain spaces) used to identify the site in the Salesforce user interface. In this example we use EmailPreferences. See screenshot below.
    • Site Name – name (cannot contain spaces) used to identify the site in code
    • Site Contact – Salesforce user who will receive email notifications about any problems with the site.
    • Default Web Address – the part of the site URL that will appear immediately after the domain name, e.g. “domainname.force.com/defaultwebaddress”.
    • Active – makes the site available for use. Can be set manually, or the Activate and Deactivate buttons on the Site page can be used to change tise setting.
    • Active Site Home Page – name of the Visualforce page that serves as the home page of the site when it is active: PublicEmailPreferences.
    • Inactive Site Home Page – name of the Visualforce page that serves as the home page of the site when it is not active: InMaintenance (automatically generated by Salesforce).
    • Site Template – name of the template that specifies the structure of all site pages: PublicSiteTemplate.
    • URL Rewriter Class – name of the class that translates public-facing URLs to internal ones: PublicEmailPreferencesURLRewriter. This class converts the public-facing contact ids into Salesforce record ids, so it provides one level of data security.
    • Clickjack Protection Level – the recommended value is compatible with the operation of the site.
Configuring new Force.com Public Site


Step 4: Adjusting Site Profile Permissions

Please proceed up with following steps:
    • On the Site Details page, click Public Access Settings.
    • Click Object Settings select Contact object and click Edit.
    • For Email Opt Out field tick Read and Edit 
    • Click Save.
    • Return to Profile Overview page select Visualforce Page Access and click Edit.
    • On the Enabled Visualforce Page list, select following pages and click Save:
      • PublicEmailPreferences
      • PublicEmailTemplate
    • Return to Profile Overview page select Apex Class Access and click Edit.
    • On the Enabled Apex Classes list, select following classes and click Save:
      • PublicEmailPreferencesController 
      • PublicEmailPreferencesURLRewriter
    • Note that the Enabled Visualforce Pages list may (and should) automatically include default pages associated with the site.
Step 5:  Test your new Force.com Site

When all done you can open the Force.com site URL an test it in action.
See how it suppose to looks like on our screenshot.


Force.com Site

Friday, January 9, 2015

How to instantly see potential duplicates on the Lead page

Over the time company's sales representatives could create Duplicated Leads in Salesforce. Often it creates awkwardness and challenges. For instance when different reps call to the same individual. As a result the company could lose the sale opportunity right from the start.

Salesforce has native “Find Duplicates” button located on the Lead layout but reps not always use it BEFORE the actual call or email to potential buyer. It also time consuming to check out every Lead.

Recently we received following request from one of our Customers: "Is it possible to see duplicates on the lead’s front page (ie without clicking find duplicates)? Sort of like how I can see open activities and activity history without scrolling down. This would save me a click every time on Find Duplicates button to check the same."

So Customer wants from one glance to see if the current Lead has potential duplicates  - without extra clicks. And only click to "Find Duplicates" button for search and merge duplicated Lead if needed.

You can find details of solution we've built below.

Solution to instantly show list of duplicated Leads on the Lead layout.

1) VF page (SeeDuplicatesLeads) to be embedded to Lead Layout. VF page shows list of potential duplicates of the current Lead. List consists of following columns: 
Name | Last Name | Company | Email | Phone | Lead Owner 

2) APEX controller uses similar to native "Find Duplicates" button's matching logic to identify Lead's duplicates (the same Lead Name OR the same Company OR the same Email OR the same Email Domain OR the same Phone).

See code samples below.

Extra note: Solution uses the Dynamic SOQL approach to avoid issues when one or more of the filed(s) used in SOQL have NULL value.

VF page: SeeDuplicatesLeads
<!-- 
Version      : 1.0
Company      : WebSolo Inc.
Date         : 01.2015
Description  : VF page "SeeDuplicatesLeads" to to instantly show list of duplicated Leads on the Lead layout
History      :             
-->
<apex:page standardController="Lead" extensions="SeeDuplicatesLeads">
     <apex:pageBlock >
        <apex:pageBlockTable value="{!LeadList}" var="tl">
            <apex:column headerValue="Name">
                <a href="/{!tl.id}" target="_top" id="{!tl.id}">{!tl.Name}</a>
            </apex:column>            
            <apex:column headerValue="Email" value="{!tl.Email}"/>
            <apex:column headerValue="Company" value="{!tl.Company}"/>
            <apex:column headerValue="Phone" value="{!tl.Phone}"/>
            <apex:column headerValue="Lead Owner" value="{!tl.Owner.Name}"/>
        </apex:pageBlockTable>
    </apex:pageBlock>   
</apex:page>

APEX Class: SeeDuplicatesLeads
/*
Version      : 1.0
Company      : WebSolo inc.
Date         : 01.2015
Description  : controller for VF page "SeeDuplicatesLeads"
History      :             
*/
public class SeeDuplicatesLeads 
{
    public id leadId {get; set;}
    public list<Lead> LeadList {get; set;}
    public SeeDuplicatesLeads(ApexPages.StandardController controller) 
    {
        leadId = ((Lead) controller.getRecord()).id;
        LeadList = new list<Lead>();
        Lead leadobj = [select id, Name, Email, Company, Phone, OwnerId, Owner.Name from Lead where id=: leadId limit 1];
        String sqlStart = 'select id, Name, Email, Company, Phone, OwnerId, Owner.Name from Lead where ';
        String sqlEnd = ' and id !=\'' + leadobj.id + '\'';
        String sqlwhere = '';
        if(leadobj.Email == null)
        {
            if(leadobj.Company == null)
            {
                if(leadobj.Phone == null)
                {
                     sqlwhere = 'Name =\'' + leadobj.Name + '\'';
                }
                else
                {
                     sqlwhere = '(Name =\'' + leadobj.Name + '\' or Phone =\'' + leadobj.Phone + '\')';
                }
            }   
            else
            {
                if(leadobj.Phone == null)
                {
                    sqlwhere = '(Name = \'' + leadobj.Name + '\' or Company =\'' +  leadobj.Company + '\')';
                }
                else
                {   
                    sqlwhere = '(Name = \'' + leadobj.Name + '\' or Company = \'' + leadobj.Company + '\' or Phone = \'' + leadobj.Phone + '\')';   
                }
            }    
        }  
        else
        {
            list<String> EmailDomain = leadobj.Email.split('@');
            list<Lead> LeadListNew = new list<Lead>();          
            if(leadobj.Company == null)
            {
                if(leadobj.Phone == null)
                {
                     sqlwhere = '(Name =\'' + leadobj.Name + '\' or Email LIKE \'' + EmailDomain[1] + '\')';
                }
                else
                {
                     sqlwhere = '(Name =\'' + leadobj.Name + '\' or Phone =\'' + leadobj.Phone + '\' or Email LIKE \'' + EmailDomain[1] + '\')';
                }
            }   
            else
            {
                if(leadobj.Phone == null)
                {
                    sqlwhere = '(Name = \'' + leadobj.Name + '\' or Company =\'' +  leadobj.Company + '\' or Email LIKE \'' + EmailDomain[1] + '\')';
                }
                else
                {   
                    sqlwhere = '(Name = \'' + leadobj.Name + '\' or Company = \'' + leadobj.Company + '\' or Phone = \'' + leadobj.Phone + '\' or Email LIKE \'' + EmailDomain[1] + '\')';   
                }
            }           
        } 
        LeadList = Database.query(sqlStart + sqlwhere + sqlEnd);                                                                                                                                                                                                                                                                                                                    
        if(LeadList.size() > 100)
        {
            list<Lead> goodLeadlist = new list<Lead>();
            Integer Igood = 100;
            for(Integer I = 0; I < Igood; I++)
            {
                goodLeadlist.add(LeadList[I]);
            }
            LeadList.clear();
            LeadList.addall(goodLeadlist);          
        }
    }
}

Thursday, August 7, 2014

Salesforce Lead Conversion - How To Specify resulted Account/Contact/Opportunity Record Types

As known when user converts a Lead, Salesforce creates new Account, Contact and Opportunity using the information from the Lead.

There is uncomfortable feature that Salesforce users struggle for a long time: "the default record type of the user converting the Lead is assigned to records created during lead conversion".

I.e. User (who's Profile has access to multiple Record Types) can not control with which Record Type Account, Contact and Optionally will be created. It always will be "Default Record Type" selected by Administrator for the User's profile. As a result Users will have to manually change Record Types for newly created records. Which is uncomfortable and takes valuable time.

There are two workarounds to enhance user experience and overcome the issue. Please find below workarounds description with analysis about their PROS and CONS.

Note: Updated 2015/02/05 with corrections related to solution #1

#1 Use Workflow Rules to update Record Type of created Account, Contact and Opportunity 

Easy to implement solution which not requires advanced Salesfroce Development skills.

Step 1: Create three picklist fields on Lead object (Expected Account Type, Expected Contact Type, Expected Opportunity Type) and populate them with Record Types names you have for Accounts, Contacts and Opportunities objects. These field will be visible to Users to let them to select Record Type they want for created after Lead Conversion records.

Step 2: Create three text fields with the same names on Accounts (Expected Account Type), Contacts (Expected Contact Type) and Opportunity (Expected Opportunity Type). These fields could be invisible for Users an will be used by workflow rules.

Step 3: Map new Leads fields to related fields on Accounts, Contacts and Opportunities objects.

Step 4:  You will have to create as many Workflow Rules and Actions for Accounts, Contacts and Opportunities as many Record Types you have in these objects. For instance if you have two Record Types for Account you will have to create two Workflows dedicated for each of them.

Set every Workflow Rule with Evaluation Criteria "Evaluate the rule when a record is created" and Rule Criteria  (for example) "Account: Expected Account Type EQUALS [YOUR RECORD TYPE NAME]. Add Action as field update to update the Record Type field to value you want to change in this particular Workflow. Repeat the same for every Account Record Type. Then do the same for Contacts and Opportunities Record Types.

Step 5: Activate Workflows and test the solution.

PROS: Pretty easy to implement. Does not require APEX coding and triggers development.
CONS: Six custom fields in four objects. Multiple (depend on your SFDC solution -  could be quite many) Workflow Rules/Actions to monitor and update if any changes required.

#2 Use APEX trigger Rules to update Record Type of created Account, Contact and Opportunity 

A little more complicated from development point of view but more efficient and easy to support solution.

Instead of the workflows this solution use a single APEX trigger with Helper class to handle all needed functionality.

Step 1: The same as above. Create three picklist fields on Lead object (Expected Account Type, Expected Contact Type, Expected Opportunity Type) and populate them with Record Types names you have for Accounts, Contacts and Opportunities objects. These field will be visible to Users to let them to select Record Type they want for created after Lead Conversion records.

Step 2: Create trigger and helper class. See code samples below.

Step 3: Test and deploy the solution to Production environment.

PROS: Easy to implement and support.
CONS: None

APEX Trigger: LeadConversionExpectedRecordTypes
/*
Version        : 1.0
Company        : Websolo inc. 
Date           : 08/2014
Description    : 
Update History :
*/
trigger LeadConversionExpectedRecordTypes on Opportunity (after insert) 
{
    Boolean uiCR = false;
     if(Test.isRunningTest())
     {
       uiCR  = true;
     }
     else
     {
      if(Trigger.new.size() == 1)
      {
       uiCR  = true;
      }
     }
     if(uiCR  == true)
     {
          for(Opportunity opp: Trigger.new)
          {
             LeadConversionExpectedRecordTypesHelper.UpdOpp(opp.id);
          }
     }
}

APEX helper class: LeadConversionExpectedRecordTypesHelper
/*
    Version        : 1.0
    Company        : Websolo inc. 
    Date           : 08/2014
    Description    : help class for LeadConversionExpectedRecordTypes trigger 
    Update History :
*/
public class LeadConversionExpectedRecordTypesHelper
{
 @future(callout = true)
 public static void UpdOpp(id oppObjID)
 {
   map mapRC = new map();
   for(RecordType a: [select Name, id from RecordType where SobjectType = 'Opportunity'])
   {
     mapRC.put(a.Name, a.id);
   }
   
   map mapRCacc = new map();
   for(RecordType a: [select Name, id from RecordType where SobjectType = 'Account'])
   {
     mapRCacc.put(a.Name, a.id);
   }   
   
   Opportunity opp = [select id, OwnerId, RecordTypeId from Opportunity where id =: oppObjID];   
   List listLead = new List();
   if(!test.isRunningTest())
   {
       listLead = [select id, Expected_Opportunity_Type__c, Expected_Account_Type__c, ConvertedAccountId  from Lead where ConvertedOpportunityId =: opp.id AND isConverted = true];
   }
   else
   {
       listLead = [select id, Expected_Opportunity_Type__c, Expected_Account_Type__c, ConvertedAccountId from Lead];        
   }   
   if(listLead.size() > 0)
   {
    if(listLead[0].Expected_Opportunity_Type__c != null)
    {
      opp.RecordTypeId = mapRC.get(listLead[0].Expected_Opportunity_Type__c);
      update opp;
    }
    if(listLead[0].ConvertedAccountId != null)
    {
      Account acc = [select id, RecordTypeId from Account where id=:listLead[0].ConvertedAccountId];
      if(listLead[0].Expected_Account_Type__c != null)
      {
        acc.RecordTypeId = mapRCacc.get(listLead[0].Expected_Account_Type__c);
        update acc;
      }
    }
   }
 }
}

Thursday, July 24, 2014

Identify Ultimate Parent in an Account Hierarchy

To build Account hierarchy Salesforce has native "Parent Account" lookup field in Account object. Unfortunately Salesfroce does not go further to provide native solution to automatically calculate "Ultimate Parent" or "Top Level Account" if you have more than two levels in Account hierarchy. As per our experience organizations have up to 5 (sometimes more)  levels of Account hierarchy.

Having such "Ultimate Parent" field will allow SFDC Users/Administrators to do a lot of advanced data exercises using grouping, summation or aggregation by the entire account tree.
For instance:
  • total sales to multi-level hierarchies
  • list of Contacts in entire account hierarchy
  • views, reports and dashboards for account families
There are a few workarounds to create such useful field. Please find below the most popular workarounds with analysis about their PROS and CONS.

#1 Use formula field to calculate Ultimate Parent Name or ID

Most obvious and popular solution. Using formula field you can determine the ultimate parent in the hierarchy. Formula below returns Ultimate Parent as a text formatted to hyperlink to use it in Account layout. Click to the link will open Ultimate Account page. This formula supports up to 10 levels of Accounts hierarchy.

IF(LEN(Parent.Name) < 1, HYPERLINK("/"&Id, Name,"_parent"), 
IF(LEN(Parent.Parent.Name) <1, HYPERLINK("/"&Parent.Id,Parent.Name,"_parent"), 
IF(LEN(Parent.Parent.Parent.Name) < 1, HYPERLINK("/"&Parent.Parent.Id,Parent.Parent.Name,"_parent"), 
IF(LEN(Parent.Parent.Parent.Parent.Name) < 1, HYPERLINK("/"&Parent.Parent.Parent.Id,Parent.Parent.Parent.Name,"_parent"),
IF(LEN(Parent.Parent.Parent.Parent.Parent.Name) < 1, HYPERLINK("/"&Parent.Parent.Parent.Parent.Id,Parent.Parent.Parent.Parent.Name,"_parent"), 
IF(LEN(Parent.Parent.Parent.Parent.Parent.Parent.Name) < 1 ,HYPERLINK("/"&Parent.Parent.Parent.Parent.Parent.Id,Parent.Parent.Parent.Parent.Parent.Name,"_parent"), 
IF(LEN(Parent.Parent.Parent.Parent.Parent.Parent.Parent.Name) < 1 ,HYPERLINK("/"&Parent.Parent.Parent.Parent.Parent.Parent.Id,Parent.Parent.Parent.Parent.Parent.Parent.Name,"_parent"), 
IF(LEN(Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Name) < 1 ,HYPERLINK("/"&Parent.Parent.Parent.Parent.Parent.Parent.Parent.Id,Parent.Parent.Parent.Parent.Parent.Parent.Parent.Name,"_parent"), 
IF(LEN(Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Name) < 1 ,HYPERLINK("/"&Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Id,Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Name,"_parent"),
IF(LEN(Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Name) < 1 ,HYPERLINK("/"&Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Id,Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Parent.Name,"_parent"), "Ultimate Parent Beyond 10 Levels"))))))))))
If needed formula could be updated to return text instead of hyperlink.

PROS: Easy to implement
CONS: Covers very limited number of use cases because the result of the formula is text. In move advanced cases you need Ultimate Account as a lookup field to use in reports, APEX code or in Roll-up formulas.

#2 Singe synchronous APEX trigger to calculate the Ultimate Parent when Account created or updated.

The trigger requires and has to calculate/re-calculate custom "Ultimate Parent" lookup field on Account object (read-only for users).

Let's consider few scenarios using following Accounts hierarchy tree as example:

Accounts hierarchy

Accounts 1 and 8 are "Ultimate or Top Accounts" (i.e. do not have parent Accounts)

Case 1: New Account created as a child of Account 3. The trigger has to calculate Account 1 as Ultimate Parent for new Account and update this Account with calculated value for "Ultimate Parent" field. This is easy recursive update.

Case 2: Account 3 updated to be the child of Account 1 instead of Account 2 (i.e. Account 3 moved up along the Account 1 hierarchy tree branch).
In this case Account 1 still Ultimate Parent for Account 3, 4 and trigger no need to update these two Accounts.

Case 3: Account 2 updated to be on the top of  the hierarchy tree  (i.e. Account 2 will become Ultimate Account for all related child Accounts).
In this case the trigger has to calculate Account 2 as Ultimate Parent for Accounts 3-7 and update these five Accounts with new Ultimate Parent. This is quite complicated recursive update. To find all impacted child Accounts the trigger will have to traverse down through Account 3 and Account 5 branches (layers) to identify all related to these branches Accounts and update them with new Ultimate Parent value.

Case 4: Account 2 updated to be the child of Account 8 instead of Account 1 (i.e. Account 2 with all related child Accounts moved to another [Account 8] hierarchy tree branch).
In this case trigger has to calculate Account 8 as Ultimate Parent for Accounts 2-7 and update these six Accounts with new Ultimate Parent value. This is also complicated recursive update which involve multiple parent to child account layers.

The most complicated part here is to traverse parent-child relationships from account to account. Unfortunately SFDC does not support such traverse so you can not do this in a single SOQL query. What you can - is to include parent.parent.parent.parent.parent.id in your SOQL select. Than loop through the result and if none of them are null - launch another SOQL query until you find a parent without parent. And then assign it as Ultimate Parent for involved Accounts.

Sounds complicated even in theory. But after number of experiments and brainstorming we finally built such trigger and even used it for a while. Unfortunately the trigger code was pretty ugly and solution (as appeared) was fragile. In particular cases - when hierarchy has a lot of parent to child account layers - trigger hits SFDC's governor limits. In cases when the trigger was able to handle governor limits it took a lot of time to finish - up to 5 seconds - this was not acceptable from performance point of view.

That's why we DO NOT recommend such approach and do not sharing here the trigger's code.

PROS: Works in not complicated SFDC implementations where accounts hierarchy does not have a lot of parent to child account layers.
CONS: Covers only limited use cases. Ugly and fragile code which apparently hits SFDC governor limits. Performance issues.

#3 Two components solution: synchronous APEX trigger and APEX batch

In this solution the trigger has to handle only inserts and updates along the single Account hierarchy tree branch (see Cases 1 and 2 above) and use overnight APEX batch to catch and calculate more complicated cases.

APEX batch class has more wider governor limits, could be launched overnight and does not have strict performance requirements.

The final solution consists of following components:
  • custom "Ultimate Parent" lookup field on Account object (read-only for users).
  • an APEX Trigger that populates "Ultimate Parent" field for new created or updated Accounts
  • scheduled APEX batch class to recalculate all Accounts to catch cases not covered by trigger (see Cases 3 and 4 above).
PROS: The solution covers all possible use cases. Stable code which does not hit SFDC governor limits. No performance issues.
CONS: In cases when Account moved to another branch (family) Ultimate Parent will be re-calculated only next night. But such scenarios happens quite rare.

APEX Trigger: SetUltimateParent
trigger SetUltimateParent on Account (before insert, before update) 
/*
Version        : 2.0
Company        : Websolo Inc. 
Description    : The trigger calculates Ultimate Parent ID ONLY for the updated/inserted Account with Hierarchy of parent Accounts to 5 levels up.

Scheduled APEX job will recalculate Ultimate Parent ID for all Account overnight to make sure they calculated properly in case if for example Account moved to another Account
*/ 
{
    list<Account> ListAcc = new list<Account>();
    set<id> idAcc = new set<id>();
    for(Account a: Trigger.new)
    {
        if(a.ParentId != null)
        {
            ListAcc.add(a);
            idAcc.add(a.id);            
        }
    }
    
    List<Account> AccUltP = [select id, Name,
                                     ParentId,
                                     Parent.ParentId,
                                     Parent.Parent.ParentId,
                                     Parent.Parent.Parent.ParentId,
                                     Parent.Parent.Parent.Parent.ParentId                                     
                                     from 
                                        Account
                                     where 
                                        ParentId != null
                                        and
                                        id IN: idAcc];   
   if(AccUltP.size() > 0)
   {                                                                        
       for(Account a: ListAcc)
       {
        for(Account b: AccUltP)
        {           
            if(a.id == b.id)
            {
                if(b.Parent.Parent.Parent.Parent.ParentId != null)
                {
                    a.Ultimate_Parent__c = b.Parent.Parent.Parent.Parent.ParentId;
                }           
                else
                {
                    if(b.Parent.Parent.Parent.ParentId != null)
                    {
                        a.Ultimate_Parent__c = b.Parent.Parent.Parent.ParentId;
                    }       
                    else
                    {
                        if(b.Parent.Parent.ParentId != null)
                        {
                            a.Ultimate_Parent__c = b.Parent.Parent.ParentId;
                        }       
                        else
                        {
                            if(b.Parent.ParentId != null)
                            {
                                a.Ultimate_Parent__c = b.Parent.ParentId;
                            }       
                            else
                            {
                                if(b.ParentId != null)
                                {
                                    a.Ultimate_Parent__c = b.ParentId;
                                }
                                else
                                {
                                    a.Ultimate_Parent__c = b.id;
                                }                               
                            }                   
                        }               
                    }           
                }                   
            }
         }
      }
   }                                    
}

APEX Batchable Class: UltimateParentUpdateBatchable
/*
Version        : 2.0
Company        : Websolo inc. 
Date           : 11/2013
Description    : This batchable class calculates Ultimate Parent for Account with Hierarchy of parent Accounts to 5 levels up.

*/ 
global class UltimateParentUpdateBatchable implements Database.Batchable<SObject>, Database.Stateful 
{
    global Database.QueryLocator start(Database.BatchableContext bc) 
    {
        return  Database.getQueryLocator([select id, Name, ParentId, Parent.ParentId, Parent.Parent.ParentId, Parent.Parent.Parent.ParentId, Parent.Parent.Parent.Parent.ParentId from Account]);
    }
    global void execute(Database.BatchableContext bc, List<SObject> batch)      
    {               
        list<Account> ListAcc = new list<Account>();
        set<id> idAcc = new set<id>();  
        for (Account a : (List<Account>) batch) 
        {
           if(a.ParentId != null)
           {
              ListAcc.add(a);
              idAcc.add(a.id);            
           }                
        }
        List<Account> AccUltP = new List<Account>();
        if(Test.isRunningTest())
        {
            Account Ac1 = new Account();
            Ac1.id = ListAcc[0].id;
            Ac1.Name = 'Test1';
            AccUltP.add(Ac1);
        }
        else
        {
                            AccUltP = [select id, Name,
                                             ParentId,
                                             Parent.ParentId,
                                             Parent.Parent.ParentId,
                                             Parent.Parent.Parent.ParentId,
                                             Parent.Parent.Parent.Parent.ParentId                                     
                                             from 
                                                Account
                                             where 
                                                ParentId != null
                                                and
                                                id IN: idAcc]; 
        }  
       if(AccUltP.size() > 0)
       {                                                                        
           for(Account a: ListAcc)
           {
            for(Account b: AccUltP)
            {           
                if(a.id == b.id)
                {
                    if(b.Parent.Parent.Parent.Parent.ParentId != null)
                    {
                        a.Ultimate_Parent__c = b.Parent.Parent.Parent.Parent.ParentId;
                    }           
                    else
                    {
                        if(b.Parent.Parent.Parent.ParentId != null)
                        {
                            a.Ultimate_Parent__c = b.Parent.Parent.Parent.ParentId;
                        }       
                        else
                        {
                            if(b.Parent.Parent.ParentId != null)
                            {
                                a.Ultimate_Parent__c = b.Parent.Parent.ParentId;
                            }       
                            else
                            {
                                if(b.Parent.ParentId != null)
                                {
                                    a.Ultimate_Parent__c = b.Parent.ParentId;
                                }       
                                else
                                {
                                    if(b.ParentId != null)
                                    {
                                        a.Ultimate_Parent__c = b.ParentId;
                                    }
                                    else
                                    {
                                        a.Ultimate_Parent__c = b.id;
                                    }                               
                                }                   
                            }               
                        }           
                    }                   
                }
             }
          }
          update ListAcc;
       }                    
    }
    global void finish(Database.BatchableContext bc) 
    {
        
    }
    private static testMethod void test() 
    {
        Test.startTest();
        Account Acc1 = new Account();
        Acc1.Name = 'Test1';
        insert Acc1;
        Account Acc2 = new Account();
        Acc2.Name = 'Test2';        
        Acc2.ParentId = Acc1.id;
        insert Acc2;
        
        Test.stopTest();     
    }       
}

APEX Batchable Class: UltimateParentUpdateBatchable
global class UltimateParentUpdateSchedulable implements Schedulable
{
    global void execute(SchedulableContext ctx) 
    {
        Database.executeBatch(new UltimateParentUpdateBatchable(), 200);
    }
    private static testMethod void test() {
        Test.startTest();
        System.schedule('UltimateParentUpdateBatchable', '0 0 0 * * ?', new UltimateParentUpdateSchedulable());
        Test.stopTest();
    }    
}

Monday, July 14, 2014

Custom Validation For Lead Conversion

To increase data quality Sales Managers encourage their Sales Representatives to gather as much as possible information about Leads before Conversion it to Contact, Account and Opportunity.

There are multiple techniques to enforce SFDC Users to enter values to all required fields before the Conversion. Let's discuss these techniques with implementation details and all its PROS and CONS.

How to enforce Sales Reps to enter values to required Lead fields before the Conversion.


#1 Make fields required on Lead layout

The most obvious and straight forward solution. But not the best one. Salesforce Lead layout allows Administrator to make some fields required (mandatory). But it's hard for Sales representative to get values for all required fields at once. In most cases Sales person can enter some data initially and then revisit the Lead record to update the rest of the important fields later.

PROS: Easy to implement
CONS: Not convenient for Users. To make any update (edit the Lead) User have to enter values in all required fields at once.

#2 Use a validation rule to fire when Lead is actually converted

Such validation rule will help to make certain fields required before converting the Lead but not require them to be entered when User edits the Lead's record.

Here is example of Validation Rule (could be adjusted to meet particular business requirements)

Rule Name:  Lead_Conversion_Validation

Error Condition Formula:
AND(IsConverted,
OR(
ISBLANK(Email),
ISBLANK(Phone),
ISBLANK(Website),
ISBLANK(TEXT(LeadSource)),
ISBLANK(TEXT(Range_of_Revenues__c)),
ISBLANK(State),
ISBLANK(Street),
ISBLANK(City),
ISBLANK(PostalCode),
ISBLANK(Country)
))

Error Message:
Please fill out following fields before conversion:
- Email
- Phone
- Full Address
- Website
- Range of Revenues
- Lead Source

PROS: Pretty easy to implement
CONS: Still not convenient for Users. The Validation Rule fires ONLY when user hit the Convert button on the Lead page, entered data on Conversion page and clicked Convert button. If something goes wrong (any required field is missed) - user will lose his time and will have to return back to the Lead page to enter missed data. Also Error Message is very general and does not really help the User to identify the missed field(s).

#3 Use workflow to update the Lead's Record Type/Layout when User enters all required for conversion fields

To build this solution you will have to create and support two Lead Record Types and related identical Lead layouts:
 - NotReadyForConversion (default) Lead Record Type and related Lead layout without Convert button
 - ReadyForConversion Record Type and related Lead layout with Convert button

Custom workflow have to check/monitor if all required fields have data.
When the necessary fields are filled out workflow action will update the Lead's Record Type to ReadyForConversion and Users will see the Lead in new layout - with Convert button.

PROS: Allows user to edit the Lead and Convert it only when all required fields are filled out.
CONS: Required two Record Type and two Layouts. Difficult to maintain - especially if you have multiple Leads Record Types/Layouts/User Profiles. Still not convenient for Users. No Error message. User can't see/check out which fields are still missing.

#4 Override the standard 'Convert' button with custom button and related VF page/Controller

SFDC Administrator/Developer can create a new custom 'Convert' button to be used on Lead layout instead of native one. Click to the button will call popup window with custom VF page and Controller to check if all required fields have data (based on particular business requirements).
  • If all required fields are filled out - embedded in VF page JavaScript will auto close the pop up window and redirect User to Conversion page.
  • If any required field(s) not filled out yet - VF page will show User Error message with information about which field(s) have to be entered. By click to Close button / or lose pop up window focus / or in 10 seconds of inactivity - close/auto close pop up window. User still on the Lead page and can enter data in missed field.
PROS: Allows user to edit the Lead and Convert it only when all required fields are filled out. User can easy check out which fields are missing to let them to convert the Lead.
CONS: Required some Force.com development. But final result worth the efforts - Sales Users are happy with the solution which help then save time and meet data quality criteria.

Solution Code Sample: (please contact us if you have questions or want to modify this solution to meet your particular business requirements)

Custom Button

Label: Convert
Object Name: Lead
Name: ConvertCustom
Behavior: Execute JavaScript
Display Type: Detail Page Button
OnClick JavaScript

var url = "/apex/Lead_Conversion_Validation?id={!Lead.Id}";
var width = "350";
var height = "350";
window.open(url, '','scrollbars=no,resizable=no,status=no,toolbar=no,menubar=no, width=' + width + ',height=' + height + ',left=' + ((window.innerWidth - width)/2) + ',top=' + ((window.innerHeight - height)/2) );

Visualforce Page: Lead_Conversion_Validation
<!--
Version        : 1.0
Company        : Websolo Inc. (websolo.ca)
Date           : 07/2014
Update History :
-->
<apex:page standardController="Lead" showHeader="false" sidebar="false" extensions="LeadConversionValidation">
<style>
h2
{
  width: 300% !important;
}
</style>
   <script>
window.onload = function(){
window.onblur = function(){window.close();}
     if(document.getElementById('sd').innerHTML == "")
     {
      var ids = document.getElementById('ids').innerHTML;
      window.opener.location.href="/lead/leadconvert.jsp?retURL=%2F" + ids + "&id=" + ids;
      window.top.close();
     }
     else
     {
         setTimeout(function(){
          window.close();
        }, 10000);   
     }
};
   </script>
      <div id="sd" style="display: none;">{!reft}</div>
      <div id="ids" style="display: none;">{!leadobjid}</div> 
 <apex:pageBlock title="Lead Conversion Validation">
      <apex:pageBlockButtons location="bottom">
       <button onclick="window.close();">Close</button>
     </apex:pageBlockButtons>
      <apex:pageMessage severity="error" strength="1">
          <apex:outputText value="{!error}" escape="false" />
          <apex:outputText value="{!sterrmsg}" escape="false" rendered="{!sterr}"/><br />         
      </apex:pageMessage>
  </apex:pageBlock>
</apex:page>


Apex Class: LeadConversionValidation
(controller - code could be adjusted to meet particular business requirements)
/*
Version        : 1.0
Company        : Websolo Inc. (websolo.ca)
Date           : 07/2014
Update History :
*/
public class LeadConversionValidation
{
    public id leadobjid {get; set;}
    public String error {get; set;}
    public String reft {get; set;}
    public Boolean sterr {get; set;}
    public String sterrmsg {get; set;}
    public LeadConversionValidation(ApexPages.StandardController controller)
    {
      sterr = false;
      sterrmsg = 'To convert Lead please change Lead Status to Contacted';
      error = 'Please fill out following fields before conversion:<br />';
      reft = '';
      leadobjid = ((Lead) controller.getRecord()).id;
      Lead leadobj = [select Status, LastName, Keywords__c, Financing_Notes__c, Email,Phone,Website,Employees__c,Rapport__c,LeadSource,Range_of_Revenues__c,State,Street,City,PostalCode,Country from Lead where id =: leadobjid ];
      if(leadobj.LastName == null ||
        leadobj.Keywords__c  == null ||
        leadobj.Financing_Notes__c == null ||
        leadobj.Email == null ||
        leadobj.Phone == null ||
        leadobj.Website == null ||
        leadobj.Employees__c == null ||
        leadobj.Rapport__c == null ||
        leadobj.LeadSource == null ||
        leadobj.Range_of_Revenues__c == null ||
        leadobj.State == null ||
        leadobj.Street == null ||
        leadobj.City == null ||
        leadobj.PostalCode == null ||
        leadobj.Country == null)
        { 
          reft = '1';
          if(leadobj.Keywords__c  == null){error = error + '- Keywords<br />';}
          if(leadobj.Financing_Notes__c  == null){error = error + '- Call Notes (at least 100 characters)<br />';}
          if(leadobj.Email == null){error = error + '- Email<br />';}
          if(leadobj.Phone == null){error = error + '- Phone<br />';}
          if(leadobj.Website == null){error = error + '- Website<br />';}
          if(leadobj.Employees__c  == null){error = error + '- Employees Range<br />';}
          if(leadobj.Rapport__c == null){error = error + '- Rapport<br />';}
          if(leadobj.LeadSource == null){error = error + '- Lead Source<br />';}
          if(leadobj.LastName == null){error = error + '- Lead Name<br />';}
          if(leadobj.Range_of_Revenues__c == null){error = error + '- Range of Revenues<br />';}
          if(leadobj.State == null || leadobj.Street == null || leadobj.City == null || leadobj.PostalCode == null || leadobj.Country == null){error = error + '- Full Address<br />';}     
        }
        if(leadobj.Status != 'Contacted')
        {
          //sterr = true;
          if(reft == '1')
          {
           sterr = true;
          }
          else
          {
           error = '';
           reft = '1';
           sterr = true;
          }
        }         
    }
}


Apex Class: TestLeadConversionValidation (test coverage)
Version        : 1.0
Company        : Websolo Inc. (websolo.ca)
Date           : 07/2014
Update History :
*/
@isTest
private class TestLeadConversionValidation
{
static testMethod void myUnitTest() 
{
Lead ld = new Lead();
ld.LastName = 'test';
ld.Company = 'test';
ld.Email = 'test@test.com';
ld.Phone = '1112223456';
insert ld;
LeadConversionValidation obj = new LeadConversionValidation(new ApexPages.StandardController(ld));
}
}