Monday 4 June 2018

Salesforce - setting opportunity targets for use on actual v target reports

Having attempted to use Salesforce's collaborative forecasting solution, which seemed perfect for indivudual quota(targets) agaisnt actual closed won amounts, i found there was an issue when trying to report actual amounts against group targets, product groups (if different from product family), company regions and using a different currency field other than opportunity amount.

There are paid for apps that provide extra flexibility, but i thought i could make use of custom summary formula and a clever way of using an opportunity formula field to set the targets.  This solutions means no extra objects are required and no need to use collaborative forecasting.

My final result displayed on the dashboard looks like this:

steps to reproduce:

1 - to set the targets on a monthly basis throughout the year:

create a formula(number) field on opportunity product



our release_code_1 field is a date field for when money is collected so for every product sold this field is populated and means we can use month() to put that value as a month value and then use case to allocate the monthly target values

2 - create report

create a opportunity / opportunity product report type with the new rd__c field included

set the main filters to all opportunities/date field as revenue release date and the date range to current cy

apply any additional filters as appropriate

in the matrix/summary report row grouping is the date field (group this field by month) and in column grouping use sum of amount or sum of net value before vat (from product) - it is here that you add custom summary formula - which i called monthly target:

your matrix would like this:



3 - add a chart on the report

for chart data you can use sum of net value or sum of amount depending on how you have previous customised currenct data in either opportunity/opportunity-products, x axis would be the date field you use in the report then check plot additional fields where display is line and value is monthly target (custom summary formula) also check use second axis

for formatting, add the legend to the bottom, check show axis label and check enable hover, also set the y-axis to manula starting at 0 and ending with the same value as the second axis (this ensures the two y axis align)  if you dont do this your target will look like its below the actual when actually the figures say target hasn't been achieved




that is it - easy 

and feel free to comment

i am actually working on a better solution where i am building a quota object where its the parent object of opportunity via a lookup on opportunity.   in this object will be the target value, the opp owner, and a rollup of opportunity amount and other currency fields on opp/opp product as well as product divisions and company regions.  i will elaborate further when that is complete, but obviously this will require code to pull data on to quota__c from opportunity and opportunity product........watch this space

Thursday 13 October 2016

Apex - Trigger.old and trigger.new comparison

trigger contacttrigger on contact (before delete) {
    for (customobject__C coj : [SELECT Contactlookup__c
                                      FROM contactrelatedobject__c
                                      WHERE Contactlookup__c
                                      IN :Trigger.oldMap.keySet()]) {
        Trigger.oldMap.get(coj.contactlookup__c).addError(
                   'Cannot delete contact with a contactrelatedobject record');
    }
}

Apex - create master-detail records

master(parent) - account

detail(child) - contact


 Creating a Child Record When a Parent Record is Created

You want to automatically create a new child record when you create a parent record. The child record should be populated with default values from contact.


trigger AutoCreatecontact on account (after insert) {
    List<contact> cons = new List<contact>();

  
    for (account newacc: Trigger.New) {
        if (newacc.customfield__c != null) {
            cons.add(new contact(
                        Name = 'Iain',
                        account = newacc.Id,
                        contactcustomfield__c = newacc.customfield__c,
                        another_contactcustomfield__c = 'Yes'));
        }
    }
    insert cons;
}


Wednesday 12 October 2016

Apex - loops

Loops are used when a particular piece of code should be repeated with desired number of iteration.

FOREACH loops let you repeatedly execute code on every element of a list:

List<Contact> allContacts = [SELECT Id FROM Contact];

for (Contact currentContact : allContacts) {
    

    currentContact.customfield__c = 'customvalue';



FOR loops  lets you repeatedly execute code a specific number of times:


for (Integer i = 0; i < 5; i++) {

    
    Contact newcontact = new Contact();
    newcontact.FirstName = 'Iain';
    newcontact.LastName  = 'Banks #' + i;
    newcontact.customfield__c = 'customvalue';
    insert newcontact;
}

FOR LOOP:
syntax - 
for (variable : list_or_set) { code_block }

List<apex_invoice__c> PaidInvoiceNumberList = new List<apex_invoice__c>();
//initialising list of object records 


PaidInvoiceNumberList = [SELECT Id,Name, APEX_Status__c FROM APEX_Invoice__c  WHERE CreatedDate = today]; 
//SOQL query to find filter records


List<string> InvoiceNumberList = new List<string>();
//list to store paid invoice


for (APEX_Invoice__c objInvoice: PaidInvoiceNumberList) { 

//loop iterates (executes repeatedly) on the PaidInvoiceNumberList and will process the each record (objInvoice)

if (objInvoice.APEX_Status__c == 'Paid') { 
//this if condition will check each record for the boolean condition



InvoiceNumberList.add(objInvoice.Name);
//if Status value is paid then it will add the invoice number into List of String
}
}

SOQL FOR LOOP:
This type of for loop is used when we don't want to create the List and directly iterate over the returned set of records of SOQL query.


Syntax - 
for (variable : [soql_query]) { code_block }
OR
for (variable_list : [soql_query]) { code_block }

the variable_list or variable should always be of same type as the records returned by the Query

List<apex_invoice__c> PaidInvoiceNumberList = new List<apex_invoice__c>();
//initialising list of object records 

List<string> InvoiceNumberList = new List<string>();
//list to store paid invoice

for (APEX_Invoice__c objInvoice: [SELECT Id,Name, APEX_Status__c FROM APEX_Invoice__c  WHERE CreatedDate = today]) { 

//this loop will iterate and will process the each record returned by the Query

if (objInvoice.APEX_Status__c == 'Paid') { 
//this if condition will check each record for the boolean condition



InvoiceNumberList.add(objInvoice.Name);
//if Status value is paid then it will add the invoice number into List of String
}
}

JAVA FOR LOOP:
Syntax - 
for (init_stmt; exit_condition; increment_stmt) { code_block }

List<apex_invoice__c> PaidInvoiceNumberList = new List<apex_invoice__c>();
//initialising list of object records 

List<string> InvoiceNumberList = new List<string>();
//list to store paid invoice

for (Integer i = 0; i < paidinvoicenumberlist.size(); i++) { 

//this loop will iterate on the List PaidInvoiceNumberList and will process the each record. It will get the List Size and will iterate the loop for number of times that size. For example, list size is 10.

if (PaidInvoiceNumberList[i].APEX_Status__c == 'Paid') { 
//this if condition will check each record for the boolean condition



InvoiceNumberList.add(PaidInvoiceNumberList[i].Name);
//if Status value is paid then it will add the invoice number into List of String
}

}

WHILE LOOP:
Syntax - 
while (Boolean_condition) { execute_code_block }

//Fetch 20 records from database
List<apex_invoice_c> InvoiceList = [SELECT Id, APEX_Description_c, APEX_Status_c FROM APEX_Invoice_c LIMIT 20];
Integer i =1;
//Update ONLY 10 records
while (i< 10) {
InvoiceList[i].APEX_Description__c = 'This is the '+i+'Invoice';

i++;

}

DO WHILE LOOP:
syntax - 
do { code_to_execute } while (Boolean_condition);


//Code for do while loop
List<apex_invoice__c> InvoiceList = [SELECT Id, APEX_Description__c, APEX_Status__c FROM APEX_Invoice__c LIMIT 20];//it will fetch only 20 records
Integer i =0;
do {
InvoiceList[i].APEX_Description__c = 'This is the '+i+' Invoice';

i++;//Increment the counter
}while (i< 1); 

//iterate till 1st record only

Sunday 11 September 2016

Apex - Usefull trigger to maintain the relationship between custom objects related to Lead to Account/Contact/Opp after Lead Conversion


trigger LeadConvertCustomObjects on Lead (before update) {
//This trigger will associate Custom Object records with the Account, Contact, and/or      opportunity associated to the
//lead after it has been converted.
//The Custom Object is associated to an opportunity only if an opportunity record exist on the Lead.
for (Integer i = 0; i < Trigger.new.size(); i++){
    if (Trigger.new[i].IsConverted == true && Trigger.old[i].isConverted == false){
        Set<Id> leadIds = new Set<Id>();
        for (Lead lead : Trigger.new)
            leadIds.add(lead.Id);

        Map<Id, DocuSign_Account__c> entries_DSA = new Map<Id, DocuSign_Account__c>([select Account__c, Lead__c from DocuSign_Account__c where lead__c in :leadIds]);      
        if(!Trigger.new.isEmpty()) {
            for (Lead lead : Trigger.new)  {
                for (DocuSign_Account__c DSA : entries_DSA.values()) {
                    if (DSA.Lead__c == lead.Id) {
                        // DSA.contact__c = lead.ConvertedContactId;
                        // DSA.opportunity__c = lead.ConvertedOpportunityId;
                        DSA.account__c = lead.ConvertedAccountId;
                        update DSA;
                        // break;
                    }
                }
            }
        }

        Map<Id, DocuSign_Account_Member__c> entries_DSAM = new Map<Id, DocuSign_Account_Member__c>([select Contact__c, Lead__c from DocuSign_Account_Member__c where lead__c in :leadIds]);      
        if(!Trigger.new.isEmpty()) {
            for (Lead lead : Trigger.new)  {
                for (DocuSign_Account_Member__c DSAM : entries_DSAM.values()) {
                    if (DSAM.Lead__c == lead.Id) {
                        DSAM.Contact__c = lead.ConvertedContactId;
                        // DSAM.opportunity__c = lead.ConvertedOpportunityId;
                        // DSAM.account__c = lead.ConvertedAccountId;
                        update DSAM;
                        // break;
                    }
                }
            }
        }

        Map<Id, Use_Case__c> entries_UC = new Map<Id, Use_Case__c>([select Account__c, Lead__c from Use_Case__c where lead__c in :leadIds]);      
        if(!Trigger.new.isEmpty()) {
            for (Lead lead : Trigger.new)  {
                for (Use_Case__c UC : entries_UC.values()) {
                    if (UC.Lead__c == lead.Id) {
                        // UC.contact__c = lead.ConvertedContactId;
                        // UC.opportunity__c = lead.ConvertedOpportunityId;
                        UC.account__c = lead.ConvertedAccountId;
                        update UC;
                        // break;
                    }
                }
            }
        }

        Map<Id, Ecosystem__c> entries_ECO = new Map<Id, Ecosystem__c>([select Account__c, Lead__c from Ecosystem__c where lead__c in :leadIds]);      
        if(!Trigger.new.isEmpty()) {
            for (Lead lead : Trigger.new)  {
                for (Ecosystem__c ECO : entries_ECO.values()) {
                    if (ECO.Lead__c == lead.Id) {
                        // ECO.contact__c = lead.ConvertedContactId;
                        // ECO.opportunity__c = lead.ConvertedOpportunityId;
                        ECO.account__c = lead.ConvertedAccountId;
                        update ECO;
                        // break;
                    }
                }
            }
        }

        Map<Id, Partner_Influence__c> entries_PI = new Map<Id, Partner_Influence__c>([select Account__c, Lead__c from Partner_Influence__c where lead__c in :leadIds]);      
        if(!Trigger.new.isEmpty()) {
            for (Lead lead : Trigger.new)  {
                for (Partner_Influence__c PI : entries_PI.values()) {
                    if (PI.Lead__c == lead.Id) {
                        // PI.contact__c = lead.ConvertedContactId;
                        PI.opportunity__c = lead.ConvertedOpportunityId;
                        PI.account__c = lead.ConvertedAccountId;
                        update PI;
                        // break;
                    }
                }
            }
        }

        Map<Id, Qualification_Credit__c> entries_QC = new Map<Id, Qualification_Credit__c>([select Account__c, Lead__c from Qualification_Credit__c where lead__c in :leadIds]);      
        if(!Trigger.new.isEmpty()) {
            for (Lead lead : Trigger.new)  {
                for (Qualification_Credit__c QC : entries_QC.values()) {
                    if (QC.Lead__c == lead.Id) {
                        // QC.contact__c = lead.ConvertedContactId;
                        QC.opportunity__c = lead.ConvertedOpportunityId;
                        QC.account__c = lead.ConvertedAccountId;
                        update QC;
                        // break;
                    }
                }
            }
        }


    }
}

}


//---------------
@isTest
//This is a test case for a situation where a lead will be converted.  The developer must explicitly call the convert lead
//method to simulate the user action.

private class TestLeadConvertCustomObjects {
    static testMethod void TestReferralUpdate() {
    // Insert the Lead
    List<Lead> leads = new List<Lead>();
    Lead leadt = new Lead (FirstName ='fname', LastName ='test', Company ='myCompany');
    insert leadt;
    // Insert the DocuSign_Account__c Record
    DocuSign_Account__c DSA = new DocuSign_Account__c (Lead__c = leadt.Id);
    insert DSA;
    // Insert the DocuSign_Account_Member__c Record
    DocuSign_Account_Member__c DSAM = new DocuSign_Account_Member__c (Lead__c = leadt.Id, DocuSign_Account__c = DSA.Id);
    insert DSAM;
    // Insert the Use_Case__c Record
    Use_Case__c UC = new Use_Case__c (Lead__c = leadt.Id, Department__c='Legal', Use_Case__c='NDAs', Status__c='Interest');
    insert UC;
    // Insert a Partner Account Record with a Partner Go To Market to relate Ecosystem & Partner Influence to
    Account PartnerAccount = new Account (Name='PartnerAccount', Partner_Go_To_Market_Count_Active__c=1);
    insert PartnerAccount;
    Partner_Go_To_Market__c PGTM = new Partner_Go_To_Market__c (Name='PartnerGoToMarket', Account__c = PartnerAccount.Id, GTM_Status__c='Agreement Signed');
    insert PGTM;
    // Insert the Ecosystem__c Record
    Ecosystem__c ECO = new Ecosystem__c (Lead__c = leadt.Id, Partner__c = PartnerAccount.Id, Ecosystem_Type__c='CRM', Integration__c='Not Integrated');
    insert ECO;
    // Insert the Partner_Influence__c Record
    Partner_Influence__c PI = new Partner_Influence__c (Lead__c = leadt.Id, Partner__c = PartnerAccount.Id, Role__c='Influencer', Influence_Type__c='Neutral');
    insert PI;
    // Insert the Qualification_Credit__c Record
    Qualification_Credit__c QC = new Qualification_Credit__c (Lead__c = leadt.Id, Status__c='Qualified');
    insert QC;

//test.startTest();

//Convert the Lead
Database.LeadConvert lc = new database.LeadConvert();
lc.setLeadId(leadt.Id);
LeadStatus convertStatus = [Select Id, MasterLabel from LeadStatus where MasterLabel='Contact Created Only' AND IsConverted=true limit 1];
lc.setConvertedStatus(convertStatus.MasterLabel);
Database.LeadConvertResult lcr = Database.convertLead(lc);  

//Requery for the referral record to see if it is updated
DocuSign_Account__c ref_upd_DSA = [select Account__c from DocuSign_Account__c where Lead__c = :leadt.Id];
DocuSign_Account_Member__c ref_upd_DSAM = [select Contact__c from DocuSign_Account_Member__c where Lead__c = :leadt.Id];
Use_Case__c ref_upd_UC = [select Account__c from Use_Case__c where Lead__c = :leadt.Id];
Ecosystem__c ref_upd_ECO = [select Account__c from Ecosystem__c where Lead__c = :leadt.Id];
Partner_Influence__c ref_upd_PI = [select Account__c, Opportunity__c from Partner_Influence__c where Lead__c = :leadt.Id];
Qualification_Credit__c ref_upd_QC = [select Account__c, Opportunity__c, Contact__c from Qualification_Credit__c where Lead__c = :leadt.Id];

//Check that the test passed
    System.assertEquals(ref_upd_DSA.Account__c,[Select ConvertedAccountId From Lead Where Id = :DSA.Lead__c].ConvertedAccountId);
    System.assertEquals(ref_upd_DSAM.Contact__c,[Select ConvertedContactId From Lead Where Id = :DSAM.Lead__c].ConvertedContactId);
    System.assertEquals(ref_upd_UC.Account__c,[Select ConvertedAccountId From Lead Where Id = :UC.Lead__c].ConvertedAccountId);
    System.assertEquals(ref_upd_ECO.Account__c,[Select ConvertedAccountId From Lead Where Id = :ECO.Lead__c].ConvertedAccountId);
    System.assertEquals(ref_upd_PI.Account__c,[Select ConvertedAccountId From Lead Where Id = :PI.Lead__c].ConvertedAccountId);
    System.assertEquals(ref_upd_QC.Account__c,[Select ConvertedAccountId From Lead Where Id = :QC.Lead__c].ConvertedAccountId);
    System.assertEquals(ref_upd_QC.Contact__c,[Select ConvertedContactId From Lead Where Id = :QC.Lead__c].ConvertedContactId);
    System.assertEquals(ref_upd_PI.Opportunity__c,[Select ConvertedOpportunityId From Lead Where Id = :PI.Lead__c].ConvertedOpportunityId);
    System.assertEquals(ref_upd_QC.Opportunity__c,[Select ConvertedOpportunityId From Lead Where Id = :QC.Lead__c].ConvertedOpportunityId);    

//Test if no opty is created
string NoOpty = 'Y';  
if (NoOpty =='Y'){
  Lead leadto = new Lead (FirstName ='fnameo', LastName ='testo', Company ='myCompanyo');
      insert leadto;
      // Insert the custom object record
      // CustomObject__c customobjecto = new CustomObject__c (Lead__c = leadto.Id);
      // insert customobjecto;
      // Insert the DocuSign_Account__c Record
      DocuSign_Account__c DSAo = new DocuSign_Account__c (Lead__c = leadto.Id);
      insert DSAo;
      // Insert the DocuSign_Account_Member__c Record
      DocuSign_Account_Member__c DSAMo = new DocuSign_Account_Member__c (Lead__c = leadto.Id, DocuSign_Account__c = DSAo.Id);
      insert DSAMo;  
      // Insert the Use_Case__c Record
      Use_Case__c UCo = new Use_Case__c (Lead__c = leadto.Id, Department__c='Legal', Use_Case__c='NDAs', Status__c='Interest');
      insert UCo;
      // Insert a Partner Account Record with a Partner Go To Market to relate Ecosystem & Partner Influence to
      Account PartnerAccounto = new Account (Name='PartnerAccounto', Partner_Go_To_Market_Count_Active__c=1);
      insert PartnerAccounto;
      Partner_Go_To_Market__c PGTMo = new Partner_Go_To_Market__c (Name='PartnerGoToMarketo', Account__c = PartnerAccounto.Id, GTM_Status__c='Agreement Signed');
      insert PGTMo;
      // Insert the Ecosystem__c Record
      Ecosystem__c ECOo = new Ecosystem__c (Lead__c = leadto.Id, Partner__c = PartnerAccounto.Id, Ecosystem_Type__c='CRM', Integration__c='Not Integrated');
      insert ECOo;
      // Insert the Partner_Influence__c Record
      Partner_Influence__c PIo = new Partner_Influence__c (Lead__c = leadto.Id, Partner__c = PartnerAccounto.Id, Role__c='Influencer', Influence_Type__c='Neutral');
      insert PIo;
      // Insert the Qualification_Credit__c Record
      Qualification_Credit__c QCo = new Qualification_Credit__c (Lead__c = leadto.Id, Status__c='Qualified');
      insert QCo;




  Database.LeadConvert lco = new database.LeadConvert();
  lco.setLeadId(leadto.Id);
  lco.isDoNotCreateOpportunity();
  lco.setDoNotCreateOpportunity(true);
  LeadStatus convertStatuso = [Select Id, MasterLabel from LeadStatus where MasterLabel='Contact Created Only' AND IsConverted=true limit 1];
  lco.setConvertedStatus(convertStatuso.MasterLabel);
  Database.LeadConvertResult lcro = Database.convertLead(lco);

  DocuSign_Account__c ref_updo_DSA = [select Account__c from DocuSign_Account__c where Lead__c = :leadto.Id];
  DocuSign_Account_Member__c ref_updo_DSAM = [select Contact__c from DocuSign_Account_Member__c where Lead__c = :leadto.Id];
  Use_Case__c ref_updo_UC = [select Account__c from Use_Case__c where Lead__c = :leadto.Id];
  Ecosystem__c ref_updo_ECO = [select Account__c from Ecosystem__c where Lead__c = :leadto.Id];
  Partner_Influence__c ref_updo_PI = [select Account__c, Opportunity__c from Partner_Influence__c where Lead__c = :leadto.Id];
  Qualification_Credit__c ref_updo_QC = [select Account__c, Opportunity__c, Contact__c from Qualification_Credit__c where Lead__c = :leadto.Id];


  //Check that the test passed
      System.assertEquals(ref_updo_DSA.Account__c,[Select ConvertedAccountId From Lead Where Id = :DSAo.Lead__c].ConvertedAccountId);
      System.assertEquals(ref_updo_DSAM.Contact__c,[Select ConvertedContactId From Lead Where Id = :DSAMo.Lead__c].ConvertedContactId);
      System.assertEquals(ref_updo_UC.Account__c,[Select ConvertedAccountId From Lead Where Id = :UCo.Lead__c].ConvertedAccountId);
      System.assertEquals(ref_updo_ECO.Account__c,[Select ConvertedAccountId From Lead Where Id = :ECOo.Lead__c].ConvertedAccountId);
      System.assertEquals(ref_updo_PI.Account__c,[Select ConvertedAccountId From Lead Where Id = :PIo.Lead__c].ConvertedAccountId);
      System.assertEquals(ref_updo_QC.Account__c,[Select ConvertedAccountId From Lead Where Id = :QCo.Lead__c].ConvertedAccountId);
      System.assertEquals(ref_updo_QC.Contact__c,[Select ConvertedContactId From Lead Where Id = :QCo.Lead__c].ConvertedContactId);
      System.assertEquals(ref_updo_PI.Opportunity__c,[Select ConvertedOpportunityId From Lead Where Id = :PIo.Lead__c].ConvertedOpportunityId);
      System.assertEquals(ref_updo_QC.Opportunity__c,[Select ConvertedOpportunityId From Lead Where Id = :QCo.Lead__c].ConvertedOpportunityId);    
      // System.assert(ref_updo__DSA.Opportunity__c == null);

//test.stopTest();
}
}

  static testMethod void testBulkUpdate() {
    List<Lead> leads = new List<Lead>();    
    for (Integer i=0;i<5;i++) {
        Lead l = new Lead (FirstName ='bulk', LastName ='Test', Company ='myCompanyo');
    insert l;
    // Insert the Custom Record
     DocuSign_Account__c DSAr = new DocuSign_Account__c (Lead__c = l.Id);
     insert DSAr;
     DocuSign_Account_Member__c DSAMr = new DocuSign_Account_Member__c (Lead__c = l.Id, DocuSign_Account__c = DSAr.Id);
     insert DSAMr;
     // Insert the Use_Case__c Record
     Use_Case__c UCr = new Use_Case__c (Lead__c = l.Id, Department__c='Legal', Use_Case__c='NDAs', Status__c='Interest');
     insert UCr;
     // Insert a Partner Account Record with a Partner Go To Market to relate Ecosystem & Partner Influence to
     Account PartnerAccountr = new Account (Name='PartnerAccountBulk', Partner_Go_To_Market_Count_Active__c=1);
     insert PartnerAccountr;
     Partner_Go_To_Market__c PGTMr = new Partner_Go_To_Market__c (Name='PartnerGoToMarketBulk', Account__c = PartnerAccountr.Id, GTM_Status__c='Agreement Signed');
     insert PGTMr;
     // Insert the Ecosystem__c Record
     Ecosystem__c ECOr = new Ecosystem__c (Lead__c = l.Id, Partner__c = PartnerAccountr.Id, Ecosystem_Type__c='CRM', Integration__c='Not Integrated');
     insert ECOr;
     // Insert the Partner_Influence__c Record
     Partner_Influence__c PIr = new Partner_Influence__c (Lead__c = l.Id, Partner__c = PartnerAccountr.Id, Role__c='Influencer', Influence_Type__c='Neutral');
     insert PIr;
     // Insert the Qualification_Credit__c Record
     Qualification_Credit__c QCr = new Qualification_Credit__c (Lead__c = l.Id, Status__c='Qualified');
     insert QCr;


      test.startTest();

      //Convert the Lead
  Database.LeadConvert lcb = new database.LeadConvert();
  lcb.setLeadId(l.Id);
  LeadStatus convertStatusb = [Select Id, MasterLabel from LeadStatus where MasterLabel='Contact Created Only' AND IsConverted=true limit 1];
  lcb.setConvertedStatus(convertStatusb.MasterLabel);
  Database.LeadConvertResult lcrb = Database.convertLead(lcb);

  DocuSign_Account__c bulkup_DSA = [select Account__c from DocuSign_Account__c where Lead__c =:l.Id];
  DocuSign_Account_Member__c bulkup_DSAM = [select Contact__c from DocuSign_Account_Member__c where Lead__c =:l.Id];
  Use_Case__c bulkup_UC = [select Account__c from Use_Case__c where Lead__c = :l.Id];
  Ecosystem__c bulkup_ECO = [select Account__c from Ecosystem__c where Lead__c = :l.Id];
  Partner_Influence__c bulkup_PI = [select Account__c, Opportunity__c from Partner_Influence__c where Lead__c = :l.Id];
  Qualification_Credit__c bulkup_QC = [select Account__c, Opportunity__c, Contact__c from Qualification_Credit__c where Lead__c = :l.Id];

  //Check that the test has passed
      System.assertEquals(bulkup_DSA.Account__c,[Select ConvertedAccountId From Lead Where Id = :DSAr.Lead__c].ConvertedAccountId);
      System.assertEquals(bulkup_DSAM.Contact__c,[Select ConvertedContactId From Lead Where Id = :DSAMr.Lead__c].ConvertedContactId);
      System.assertEquals(bulkup_UC.Account__c,[Select ConvertedAccountId From Lead Where Id = :UCr.Lead__c].ConvertedAccountId);
      System.assertEquals(bulkup_ECO.Account__c,[Select ConvertedAccountId From Lead Where Id = :ECOr.Lead__c].ConvertedAccountId);
      System.assertEquals(bulkup_PI.Account__c,[Select ConvertedAccountId From Lead Where Id = :PIr.Lead__c].ConvertedAccountId);
      System.assertEquals(bulkup_QC.Account__c,[Select ConvertedAccountId From Lead Where Id = :QCr.Lead__c].ConvertedAccountId);
      System.assertEquals(bulkup_QC.Contact__c,[Select ConvertedContactId From Lead Where Id = :QCr.Lead__c].ConvertedContactId);
      System.assertEquals(bulkup_PI.Opportunity__c,[Select ConvertedOpportunityId From Lead Where Id = :PIr.Lead__c].ConvertedOpportunityId);
      System.assertEquals(bulkup_QC.Opportunity__c,[Select ConvertedOpportunityId From Lead Where Id = :QCr.Lead__c].ConvertedOpportunityId);    
      // System.assertEquals(bulkup.Opportunity__c,[Select ConvertedOpportunityId From Lead Where Id = :r.Lead__c].ConvertedOpportunityId);


     }
  }
}

Sunday 19 June 2016

Visualforce - create an event record using a custom button and visualforce page

visual force page to create event record

requires
visualforce page
controller class
button

visualforce page

<apex:page standardController="Event" extensions="macalendarentry" showheader="false" sidebar="false">
<apex:form >
<apex:pageblock title="MArket Appraisal Calendar Entry" mode="edit">
 <apex:pageBlockButtons location="top">
 <apex:commandButton action="{!save}" value="Save"/>


 </apex:pageBlockButtons>


<apex:pageBlockSection title="Calendar Details" columns="4" >


<apex:inputfield value="{!Event.Ownerid}" >
</apex:inputfield>



<apex:inputfield value="{!Event.Subject}" >
</apex:inputfield>

<apex:inputfield value="{!Event.WhatId}" >
</apex:inputfield>

<apex:inputfield value="{!Event.Type}" >
</apex:inputfield>

<apex:inputfield value="{!Event.StartDateTime}" >
</apex:inputfield>

<apex:inputfield value="{!Event.EndDateTime}" >
</apex:inputfield>
<apex:inputfield value="{!Event.Event_Status__c}" >
</apex:inputfield>
<apex:inputfield value="{!Event.Cancellation_Reason__c}" >
</apex:inputfield>
<apex:inputfield value="{!Event.Location}" >
</apex:inputfield>
<apex:inputfield value="{!Event.ShowAs}" >
</apex:inputfield>

</apex:pageBlockSection>


<apex:pageBlockSection title="Other Information" columns="4">
<apex:inputfield value="{!Event.Location}" >
</apex:inputfield>
<apex:inputfield value="{!Event.ShowAs}" >
</apex:inputfield>
</apex:pageBlockSection>

<apex:pageBlockSection title="Description Information" columns="4">
<apex:inputfield value="{!Event.Description}" >
</apex:inputfield>
</apex:pageBlockSection>
</apex:pageblock>


</apex:form>
</apex:page>

controller
(to prepopulate values in edit screen)
public class macalendarentry {
   public event event{get;set;}
    public macalendarentry(ApexPages.StandardController stdController){

        if(event == null) event = new Event();
        event.ownerid = ApexPages.currentPage().getParameters().get('ownerID');
        event.whatid = ApexPages.currentPage().getParameters().get('whatid');
     
    }
}

button
execute javascript/onclick javascript
window.open('/apex/ADD2Calendar?whatid={!Easy_Opportunity__c.Id}&ownerid={!$User.Id}', '_blank', 'toolbar=0,location=0,menubar=0');

Thursday 16 June 2016

Visualforce - google maps

visual force - google maps visualforce page

fields required:

formula text
Coordinates__c
text( GPS_Coordinates__Latitude__s )&" "&Text(GPS_Coordinates__Longitude__s )

geolocation
GPS_Coordinates__c
decimal 7 places

visualforce page

<apex:page standardController="pba__Property__c">

<head>

<script type="text/javascript" src="https://maps.google.com/maps/api/js?&sensor=false"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function() {

  var myOptions = {
  draggable: false,
    zoom: 18,
    mapTypeId: google.maps.MapTypeId.SATELLITE,
    mapTypeControl: false
  }

  var map;
  var marker;

  var geocoder = new google.maps.Geocoder();

 
   var address = "{!pba__Property__c.Coordinates__c}";

 var infowindow = new google.maps.InfoWindow({
    content: "<b>{!pba__Property__c.pba__Address_pb__c}</b><br>{!pba__Property__c.pba__City_pb__c}<br>{!pba__Property__c.State__c}, {!pba__Property__c.pba__PostalCode_pb__c}<br>{!pba__Property__c.Country__c}"
  });

 

   geocoder.geocode( { address: address}, function(results, status) {

    if (status == google.maps.GeocoderStatus.OK && results.length) {
      if (status != google.maps.GeocoderStatus.ZERO_RESULTS) {

        //create map
        map = new google.maps.Map(document.getElementById("map"), myOptions);

        //center map
        map.setCenter(results[0].geometry.location);

        //create marker
        marker = new google.maps.Marker({
            position: results[0].geometry.location,
            map: map,
            title: "Property"
        });

        //add listeners
        google.maps.event.addListener(marker, 'click', function() {
          infowindow.open(map,marker);
        });
        google.maps.event.addListener(infowindow, 'closeclick', function() {
          map.setCenter(marker.getPosition());
        });

      }

    } else {
      $('#map').css({'height' : '25px'});
      $('#map').html("Oops! Property's  address could not be found, please make sure the address is correct.");
      resizeIframe();
    }
  });

  function resizeIframe() {
    var me = window.name;
    if (me) {
      var iframes = parent.document.getElementsByName(me);
      if (iframes && iframes.length == 1) {
        height = document.body.offsetHeight;
        iframes[0].style.height = height + "px";
      }
    }
  }

});
</script>

<style>
#map {
  font-family: Arial;
  font-size:12px;
  line-height:normal !important;
  height:250px;
  background:transparent;
}
</style>

</head>

<body>
<div id="map"></div>
</body>
</apex:page>