• raman123
  • NEWBIE
  • 55 Points
  • Member since 2019

  • Chatter
    Feed
  • 0
    Best Answers
  • 1
    Likes Received
  • 0
    Likes Given
  • 9
    Questions
  • 7
    Replies
When a new person account is created, check if there are existing unconverted leads with the same email address.
If any lead is found, convert lead using the same account which is creating it. If there are multiple leads found, first merge to latest modified lead. (Merge can only happen for max 3 leads as per Salesforce Limit. If we have more duplicates lead, we might have to consider using batch). 
If no leads found, do nothing.

code
public class AccountTriggerHandler {
    public static void existingunconvertedleads (List<Account> lstInsertedAccount){
        map<string,Account> mapOfAccount = new map<string,Account>();
        
        // Check to see if Email already exists
        for (Account a : lstInsertedAccount) {
            if(a.IsPersonAccount){
                if(String.isnotBlank(a.PersonEmail)){
                    mapOfAccount.put(a.PersonEmail,a);
                }
            }
        }
        Map<string,List<Lead>> mapOfLeadWithEmail = new Map<string,List<Lead>>();
        for(lead objld :[select id,email from lead where IsConverted = false And Email in: mapOfAccount.keySet()]){
            if(mapOfLeadWithEmail.containsKey(objld.Email)){
                List<lead> ldlist =  mapOfLeadWithEmail.get(objld.Email);
                ldlist.add(objld);
                mapOfLeadWithEmail.put(objld.Email,ldlist);
            } else{
                mapOfLeadWithEmail.put(objld.Email, new list<lead>{objld});   
            }
            
        }
        
        
        for(string strEmail: mapofLeadWithEmail.keyset()){
            if(mapofLeadWithEmail.get(strEmail).size() > 1){
              list<lead> ls = [select id from lead where id =:mapOfLeadWithEmail.keyset()];
                
                
                LeadStatus CLeadStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true];
                List<Database.LeadConvert> MassLeadconvert = new List<Database.LeadConvert>();
                for(id currentlead: mapOfAccount.keyset()){
                    Database.LeadConvert Leadconvert = new Database.LeadConvert();
                    Leadconvert.setLeadId(currentlead);                
                    Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                    MassLeadconvert.add(Leadconvert);
                    if (!MassLeadconvert.isEmpty()) {
                        List<Database.LeadConvertResult > lcr = Database.convertLead(MassLeadconvert);
                    }
                } 
            }
               
            
            system.debug('strEmail ::: '+strEmail);
            system.debug('Lead size ::: '+mapofLeadWithEmail.get(strEmail).size());
        }
    }
}
public class ExtensionVoucherHandler {
   public static Boolean doRun = True;
  public static void VoucherResend(Map <id,Certification_Voucher__c> oldMap, list<Certification_Voucher__c> newlist ){
  
  map<string,Certification_Voucher__c> codemap = new map<string,Certification_Voucher__c>();

   for(Certification_Voucher__c C : newlist){
   
      if(C.Expiration_Date__c != oldMap.get(C.id).Expiration_Date__c){
        
        codemap.put(C.name,C);
     
     }
   
   }
   
   List<Training_Attendee__c> TA = [select id,Voucher_Code__c,Voucher_Expiration_Date__c from Training_Attendee__c where Voucher_Code__c in: codemap.keyset()];
     
   List<Training_Attendee__c> lstUpdate = new List<Training_Attendee__c>();    
       
        for(Training_Attendee__c  train : TA){
        
            if(codemap.containsKey(train.Voucher_Code__c)){
              train.Voucher_Expiration_Date__c = codemap.get(train.Voucher_Code__c).Formatted_Expiration_Date__c ;
               lstUpdate.add(train);
          }
     }
      if(lstupdate != null && lstupdate.size() > 0)     
     database.update (lstUpdate,false);
     
     }
   }
global class UpdateExchange_Rate_Advanced_on_Oppty implements Database.Batchable<sObject>,Database.Stateful,schedulable {
    
    public String query; 
    
    global UpdateExchange_Rate_Advanced_on_Oppty() {
        
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC) {
        
        if(String.isBlank(query)) {
            
            query = 'Select Id, CloseDate, CurrencyISOCode,Amount, Amount_USD__c ,Exchange_Rate_Advanced__c from  Opportunity where Exchange_Rate_Advanced__c = null';
        } 
        
        return Database.getQueryLocator(query); 
    }

    global void execute(Database.BatchableContext BC, List<Opportunity> scope) {
        
        Date oppMinDate;
        Date oppMaxDate;
        Set<String> isoCodes = new Set<String>();
        List<Opportunity> newOpps = new List<Opportunity>();
        List<Opportunity> forUpdateOpps = new List<Opportunity>();
        
        for(Opportunity opp: scope) 
        {
                System.debug('Inside for 1');
                isoCodes.add(opp.CurrencyISOCode);
                
                if(oppMinDate == null || opp.CloseDate<oppMinDate)
                    oppMinDate = opp.CloseDate;
                if(oppMaxDate == null || opp.CloseDate>oppMaxDate)
                    oppMinDate = opp.CloseDate;    
                
                newOpps.add(opp);                
            
        }
        isoCodes.remove(null);
        
        if(newOpps.size()>0){
            Map<String,List<DatedConversionRate>> conversionRateMap = new Map<String,List<DatedConversionRate>>();
            Date nxtStartDate = date.newInstance(999, 12, 31);
            
            for(DatedConversionRate dcr:[SELECT ISOCode, ConversionRate, NextStartDate, StartDate FROM DatedConversionRate 
                            Where ISOCode in :isoCodes AND 
                            ( NextStartDate = 9999-12-31 OR 
                                (StartDate <=: oppMinDate AND NextStartDate >=: oppMinDate) OR (StartDate <=: oppMaxDate AND NextStartDate >=: oppMaxDate) 
                            ) ORDER BY StartDate DESC])
            {                    
                if(dcr.NextStartDate == nxtStartDate)
                    conversionRateMap.put(dcr.ISOCode+'9999-12-31',new List<DatedConversionRate>{dcr});
                else if(conversionRateMap.containsKey(dcr.ISOCode))
                    conversionRateMap.get(dcr.ISOCode).add(dcr);
                else
                    conversionRateMap.put(dcr.ISOCode,new List<DatedConversionRate>{dcr});
            }
            
            for(Opportunity opp: newOpps) {
                Decimal conversionRate;
                
                if(conversionRateMap.containsKey(opp.CurrencyISOCode)){
                    Boolean matched = false;
                    for(DatedConversionRate dcr : conversionRateMap.get(opp.CurrencyISOCode)){
                        if(dcr.StartDate <= opp.CloseDate && dcr.NextStartDate >= opp.CloseDate){
                            conversionRate = dcr.conversionRate;
                            matched = true;
                            break;
                        }
                    }
                    if(!matched)
                        conversionRate = conversionRateMap.get(opp.CurrencyISOCode+'9999-12-31')[0].ConversionRate;
                }else
                    conversionRate = conversionRateMap.get(opp.CurrencyISOCode+'9999-12-31')[0].ConversionRate;
                    
                opp.Amount_USD__c = 0.00; 
                if(opp.Amount != null)
                    opp.Amount_USD__c = opp.Amount / conversionRate;             
                
                opp.Exchange_Rate_Advanced__c = conversionRate;   
                
                forUpdateOpps.add(opp);
            }
            
            if(forUpdateOpps.size()>0)
            {
                database.update(forUpdateOpps, false);
            }
        }
        
    }
    
    global void finish(Database.BatchableContext BC) {
        
    }

    // Schedule the Batch Apex Class
    global void execute(SchedulableContext sc) {
        Id batchId = Database.executeBatch(new UpdateExchange_Rate_Advanced_on_Oppty(), 10);
    }
    
}

test class
@isTest(SeeAllData = false)
public  with sharing class Test_UpdateExchange_Rate_Adv_on_Oppty {

    public static testMethod void test(){
      Account acc = new Account(name = 'test Account', CurrencyIsoCode = 'USD', Region__c = 'APAC',   BillingCountry = 'United State', BillingState='WV');
        insert acc;
        
        
        Opportunity opp = new Opportunity(Name = 'oppName', AccountId = acc.Id, Forecast_Status__c = 'Funnel', StageName = 'Problem Identified', Region__c = 'APAC',
                                                Registered_Partner_Opportunity__c = 'No Partner', CloseDate = System.Today().addDays(1), Target_Group__c = 'Core');
        
        
        insert opp;     
        
        
                 
        Test.startTest();
       
      Id batchId = Database.executeBatch(new UpdateExchange_Rate_Advanced_on_Oppty(), 1);
    Test.stopTest();
    }
}
function showBox() {

var box = new parent.SimpleDialog("helder"+Math.random(), true);
parent.box = box;

box.setTitle("Sales Coach - Stage: {!TSGADX__Deal__c.TSGADX__Sales_Stage__c}");

box.createDialog();
box.setWidth(900);
box.setContentInnerHTML("<a href=\"#\" onclick=\"box.hide();\">Close</a><br/><iframe src =\"/apex/TSGADX__SalesCoachV2?id={!TSGADX__Deal__c.Id}\" height=\"700\" width=\"950\" frameborder=\"0\" style=\"border:none; width:850px; margin-left:0; margin-right: auto; height:600px;overflow-x:hidden;\"><p>Your browser does not support iframes.</p></iframe>");

box.setupDefaultButtons();

box.show();

}

showBox();
my code where it ppopulate the hourly rate field of team object from user hourly rate field if team hourly rate is null
trigger populate1 on Team__c (before insert , before update){ 
   Set<Id> idOwnerSet = new Set<Id>();
    List<Team__c> projectList = new List<Team__c>(); 
    for(Team__c obj : trigger.new)
    {
        if(obj.hourly_rate__c == null) {
            
            idOwnerSet.add(obj.Id);
            projectList.add(obj);
        }
       
    }    
    
    if(projectList.isEmpty()) return;
    
    Map<Id, User> userMap = new Map<Id, User>([SELECT Id, hourly_rate__c FROM User WHERE Id = :idOwnerSet]);
    
    if(userMap.isEmpty()) return;
    
    for(Team__c proj : projectList)
    {
        proj.hourly_rate__c = null;
        if(userMap.get(proj.Id).City != null)
        {
            proj.hourly_rate__c = userMap.get(proj.Id).hourly_rate__c;
        }
    }
      
}
my test class
@istest
public class testpopulate1 {
   @istest static  void checkrate(){
    team__c  proj= new team__c();
       proj.hourly_rate__c = null;
       insert proj;
      Profile pf= [Select Id from profile where Name='System Administrator'];

       User u = new User(
     LastName = 'last',
     Email = 'puser000@amamama.com',
     Username = 'puser000@amamama.com' + System.currentTimeMillis(),
     CompanyName = 'TEST',
     Title = 'title',
     Alias = 'alias',
     TimeZoneSidKey = 'America/Los_Angeles',
     EmailEncodingKey = 'UTF-8',
     LanguageLocaleKey = 'en_US',
     LocaleSidKey = 'en_US',
     city = 'Usa',
     hourly_rate__c = 30,
     ProfileId = pf.Id);
      insert u;
      
     system.assert(proj.hourly_rate__c == 30 );
      
   }


}
trigger Trigger_case_Send_Email on case (after update) {
        List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();   
        Set<Id> ownerIds = new Set<Id>();
   
        for (case mycase : Trigger.new) {

        case oldcon = Trigger.oldMap.get(mycase.Id);
        
    
        if (mycase.ownerid != oldcon.ownerid ) {

        ownerids.add(oldcon.ownerid) ; 

 }
    
        Map<Id, User> userMap = new Map<Id,User>([select Name, Email from User where Id in :ownerIds]);
        for(case cas : Trigger.old)
    {
        User theUser = userMap.get(cas.ownerId);
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new string []{theuser.Email};
        mail.setToAddresses(toAddresses);   
        mail.setSubject('A case owned by you has been transfer');   
        string mailBody = 'Link: '+ URL.getSalesforceBaseUrl().toExternalForm()+ '/'+Cas.Id;
        mail.setPlainTextBody(mailBody);
        mails.add(mail);
        
            
    }
   Messaging.SendEmail(mails);
   }
   }
trigger populate on project__c (before insert , before update){
 
    
    
     MAP<ID , user> mapCon = new MAP<ID , user>([Select id ,name,city
                                                 from user 
]);
     for(project__c  obj : trigger.new)
       {
        if(obj.delivery_location__c == null)
          {
           user u  = mapcon.get(obj.ownerid);
              if (u.city != null)
              
             obj.Delivery_location__c=u.city;
              else {
                   obj.Delivery_location__c = 'NA';
              }
          }
       
       }
       
       }
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
List<ID>ownerids=new List<ID>();

List<String> sendTo = new List<String>();
List<User>users=new List<User>();

for (case mycase : Trigger.new) {

    case oldcon = Trigger.oldMap.get(mycase.Id)
        
    
 if (mycase.ownerid != oldcon.ownerid ) {

     ownerids.add(oldcon.ownerid) ; 

     }
    }

   users=[select name,id,email from user where id in:ownerids];
    for(User u:users){

      sendTo.add(u.Email); 

    }

    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setSenderDisplayName('Email alert');
mail.setSubject('Owner change');
String body = 'Dear User Owner changed';
mail.setToAddresses(sendTo);
mail.setPlainTextBody(body);
mails.add(mail);
Messaging.sendEmail(mails);
When a new person account is created, check if there are existing unconverted leads with the same email address.
If any lead is found, convert lead using the same account which is creating it. If there are multiple leads found, first merge to latest modified lead. (Merge can only happen for max 3 leads as per Salesforce Limit. If we have more duplicates lead, we might have to consider using batch). 
If no leads found, do nothing.

code
public class AccountTriggerHandler {
    public static void existingunconvertedleads (List<Account> lstInsertedAccount){
        map<string,Account> mapOfAccount = new map<string,Account>();
        
        // Check to see if Email already exists
        for (Account a : lstInsertedAccount) {
            if(a.IsPersonAccount){
                if(String.isnotBlank(a.PersonEmail)){
                    mapOfAccount.put(a.PersonEmail,a);
                }
            }
        }
        Map<string,List<Lead>> mapOfLeadWithEmail = new Map<string,List<Lead>>();
        for(lead objld :[select id,email from lead where IsConverted = false And Email in: mapOfAccount.keySet()]){
            if(mapOfLeadWithEmail.containsKey(objld.Email)){
                List<lead> ldlist =  mapOfLeadWithEmail.get(objld.Email);
                ldlist.add(objld);
                mapOfLeadWithEmail.put(objld.Email,ldlist);
            } else{
                mapOfLeadWithEmail.put(objld.Email, new list<lead>{objld});   
            }
            
        }
        
        
        for(string strEmail: mapofLeadWithEmail.keyset()){
            if(mapofLeadWithEmail.get(strEmail).size() > 1){
              list<lead> ls = [select id from lead where id =:mapOfLeadWithEmail.keyset()];
                
                
                LeadStatus CLeadStatus = [SELECT Id, MasterLabel FROM LeadStatus WHERE IsConverted=true];
                List<Database.LeadConvert> MassLeadconvert = new List<Database.LeadConvert>();
                for(id currentlead: mapOfAccount.keyset()){
                    Database.LeadConvert Leadconvert = new Database.LeadConvert();
                    Leadconvert.setLeadId(currentlead);                
                    Leadconvert.setConvertedStatus(CLeadStatus.MasterLabel);
                    MassLeadconvert.add(Leadconvert);
                    if (!MassLeadconvert.isEmpty()) {
                        List<Database.LeadConvertResult > lcr = Database.convertLead(MassLeadconvert);
                    }
                } 
            }
               
            
            system.debug('strEmail ::: '+strEmail);
            system.debug('Lead size ::: '+mapofLeadWithEmail.get(strEmail).size());
        }
    }
}
public class ExtensionVoucherHandler {
   public static Boolean doRun = True;
  public static void VoucherResend(Map <id,Certification_Voucher__c> oldMap, list<Certification_Voucher__c> newlist ){
  
  map<string,Certification_Voucher__c> codemap = new map<string,Certification_Voucher__c>();

   for(Certification_Voucher__c C : newlist){
   
      if(C.Expiration_Date__c != oldMap.get(C.id).Expiration_Date__c){
        
        codemap.put(C.name,C);
     
     }
   
   }
   
   List<Training_Attendee__c> TA = [select id,Voucher_Code__c,Voucher_Expiration_Date__c from Training_Attendee__c where Voucher_Code__c in: codemap.keyset()];
     
   List<Training_Attendee__c> lstUpdate = new List<Training_Attendee__c>();    
       
        for(Training_Attendee__c  train : TA){
        
            if(codemap.containsKey(train.Voucher_Code__c)){
              train.Voucher_Expiration_Date__c = codemap.get(train.Voucher_Code__c).Formatted_Expiration_Date__c ;
               lstUpdate.add(train);
          }
     }
      if(lstupdate != null && lstupdate.size() > 0)     
     database.update (lstUpdate,false);
     
     }
   }
trigger populate on project__c (before insert , before update){
 
    
    
     MAP<ID , user> mapCon = new MAP<ID , user>([Select id ,name,city
                                                 from user 
]);
     for(project__c  obj : trigger.new)
       {
        if(obj.delivery_location__c == null)
          {
           user u  = mapcon.get(obj.ownerid);
              if (u.city != null)
              
             obj.Delivery_location__c=u.city;
              else {
                   obj.Delivery_location__c = 'NA';
              }
          }
       
       }
       
       }
List<Messaging.SingleEmailMessage> mails = new List<Messaging.SingleEmailMessage>();
List<ID>ownerids=new List<ID>();

List<String> sendTo = new List<String>();
List<User>users=new List<User>();

for (case mycase : Trigger.new) {

    case oldcon = Trigger.oldMap.get(mycase.Id)
        
    
 if (mycase.ownerid != oldcon.ownerid ) {

     ownerids.add(oldcon.ownerid) ; 

     }
    }

   users=[select name,id,email from user where id in:ownerids];
    for(User u:users){

      sendTo.add(u.Email); 

    }

    Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setSenderDisplayName('Email alert');
mail.setSubject('Owner change');
String body = 'Dear User Owner changed';
mail.setToAddresses(sendTo);
mail.setPlainTextBody(body);
mails.add(mail);
Messaging.sendEmail(mails);