Thursday, 28 June 2018

Salesforce - Data Aggregation with Apex

global class LeadSharePerformanceTrackBatch implements Database.Batchable<sObject>,Database.Stateful, Schedulable {
    public List<Round_Robin_Client__c> round_robin_list;
    global void scheduleMe() {
        String CRON=System.Label.LeadSharePerformanceTrackBatch_CRON;
        //Run the batch daily at 10 PM
        system.schedule('LeadSharePerformanceTrackBatch__'+DateTime.now(), CRON, new LeadSharePerformanceTrackBatch());   
    }
    global void execute(SchedulableContext sc){
        LeadSharePerformanceTrackBatch batch=new LeadSharePerformanceTrackBatch();
        ID batchprocessid=Database.executeBatch(batch);
    }
    //query RoundRobin records
    global Database.QueryLocator start(Database.BatchableContext BC) {       
        round_robin_list=new List<Round_Robin_Client__c>();
        //Query RoundRobin with recently created 90 Leadshares
        String query = 'SELECT '+ showFields('Round_Robin_Client__c')+         
            ', (SELECT Id,assigned__c,round_robin__c,date__c FROM Leadshare__r ORDER BY lastmodifieddate DESC LIMIT 90) '+
            'FROM Round_Robin_Client__c '+
            'WHERE Active_Lead_Type__c!=NULL'+
            ' AND Status__c=\'Active\'';
        System.debug('query: '+query);
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Round_Robin_Client__c> scope) {
        //Add all records of each batch
        round_robin_list.addAll(scope);
    } 
    global void finish(Database.BatchableContext BC) {
        Set<Id> spIdset=new Set<Id>();
        set<String> leadtypeset=new Set<String>();
        for(Round_Robin_Client__c rc:round_robin_list){
            spIdset.add(rc.originator__c);
            leadtypeset.add(rc.Active_Lead_Type__c);
        }
        //Create Leadshare records
        List<Leadshare__c> leadshares=getLeadSharesWithStatistics(getNewLeadshares(round_robin_list),spIdset,leadtypeset);
        if(leadshares.size()>0){
            insert leadshares;
            System.debug('Total Leadshares created today: '+leadshares.size());
        }     
    }
    public String showFields(String sobjectname) {
        //fields.clear();
        String fields='';
        system.debug('name' + sobjectname);
        Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        Map <String, Schema.SObjectField> fieldMap =  schemaMap.get(sobjectname).getDescribe().fields.getMap();
        for(Schema.SObjectField sfield : fieldMap.Values())
        {
            schema.describefieldresult dfield = sfield.getDescribe();
            // system.debug(dfield.getname()+'=>'+dfield.getLabel());
            fields+=dfield.getName()+',';
        }
        fields=fields.removeEnd(',');
        System.debug('fields: '+fields);
        return fields;
    } 
    public static List<LeadShare__c> getLeadSharesWithStatistics(List<LeadShare__c> p_lslist,Set<Id> p_spIdset,Set<String> p_leadtypeset){
        List<LeadShare__c> parentList = p_lslist;
        List<LeadShare__c> leadshare_list = new List<LeadShare__c>();   
        Set<String> stagesSet=new Set<String>();
        Set<Id> salesRepIdSet=new Set<Id>();
        Set<String> leadActiveTypeset=new Set<String>();
        // Include selective stages for calculation
        stagesSet=new Set<String>{'Initial Contact','Invalid Lead','Lost','Closed','Initial - to Retry','Overcome Objections','Ready to Close','Promised To Buy'};
    salesRepIdSet=p_spIdset;
        leadActiveTypeset=p_leadtypeset;
        Map<String,Integer> TotalLeadsMap=new Map<String,Integer>();
        for(AggregateResult ar:[SELECT count(Id) counter,Sales_Rep__c,Primary_Interest__c
                                FROM SEOX3_Client__c
                                WHERE Sales_Rep__c IN:salesRepIdSet
                                AND Prospective_Stage__c IN:stagesSet
                                AND Primary_Interest__c IN:p_leadtypeset
                                group by Sales_Rep__c,Primary_Interest__c]){
                                    TotalLeadsMap.put((String)ar.get('Sales_Rep__c')+'_'+(String)ar.get('Primary_Interest__c'),(Integer)ar.get('counter'));
                                }
        System.debug('TotalLeadsMap: '+TotalLeadsMap);
       
         Map<String,Integer> TotalLeadsTodayMap=new Map<String,Integer>();
        for(AggregateResult ar:[SELECT count(Id) counter,Sales_Rep__c,Primary_Interest__c,Lastmodified_Date_part__c
                                FROM SEOX3_Client__c
                                WHERE Sales_Rep__c IN:salesRepIdSet
                                AND Prospective_Stage__c IN:stagesSet
                                AND Primary_Interest__c IN:p_leadtypeset
                                group by Sales_Rep__c,Primary_Interest__c,Lastmodified_Date_part__c]){
                                    TotalLeadsTodayMap.put(ar.get('Sales_Rep__c')+'_'+ar.get('Primary_Interest__c')+'_'+ar.get('Lastmodified_Date_part__c'),(Integer)ar.get('counter'));
                                }
        System.debug('TotalLeadsTodayMap: '+TotalLeadsTodayMap);
       
        //Getting Count of client record on the Basis of Prospective_Stage__c.
        List<AggregateResult> arrList = [SELECT COUNT(Id) counter, Prospective_Stage__c,Primary_Interest__c,Sales_Rep__c,Lastmodified_Date_part__c 
                                         FROM SEOX3_Client__c
                                         WHERE Sales_Rep__c IN:salesRepIdSet
                                         AND Prospective_Stage__c IN:stagesSet
                                         AND Primary_Interest__c IN:p_leadtypeset
                                         group by Prospective_Stage__c, Primary_Interest__c,Sales_Rep__c,Lastmodified_Date_part__c];
       
        //Map For getting StageName and its count.
        Map<String, Integer> prospectiveStagesMap = new Map<String, Integer>();       
        //Filling Stage and count in Map.
        for (AggregateResult ar : arrList) {                       
            prospectiveStagesMap.put(ar.get('Prospective_Stage__c')+'_'+ar.get('Sales_Rep__c')+'_'+ar.get('Primary_Interest__c')+'_'+ar.get('Lastmodified_Date_part__c'),(Integer)ar.get('counter'));
        }
        System.debug('prospectiveStagesMap: '+prospectiveStagesMap); 
       
        // if (!Test.isRunningTest()){
        for(LeadShare__c ls : parentList){
            // Initial Contact (Uncalled) %
            if(prospectiveStagesMap.get('Initial Contact'+'_'+ls.Sales_Rep__c+'_'+ls.Active_Lead_Type__c+'_'+ls.Date__c) != null )
                ls.Initial_Contact__c = prospectiveStagesMap.get('Initial Contact'+'_'+ls.Sales_Rep__c+'_'+ls.Active_Lead_Type__c+'_'+ls.Date__c);
            else
                ls.Initial_Contact__c = 0;
            // Invalid %
            if(prospectiveStagesMap.get('Invalid Lead'+'_'+ls.Sales_Rep__c+'_'+ls.Active_Lead_Type__c+'_'+ls.Date__c) != null )
                ls.Invalid_Lead__c = prospectiveStagesMap.get('Invalid Lead'+'_'+ls.Sales_Rep__c+'_'+ls.Active_Lead_Type__c+'_'+ls.Date__c);
            else
                ls.Invalid_Lead__c = 0;
            // Lost %
            if(prospectiveStagesMap.get('Lost'+'_'+ls.Sales_Rep__c+'_'+ls.Active_Lead_Type__c+'_'+ls.Date__c) != null )
                ls.Lost__c = prospectiveStagesMap.get('Lost'+'_'+ls.Sales_Rep__c+'_'+ls.Active_Lead_Type__c+'_'+ls.Date__c);
            else
                ls.Lost__c = 0;
            // Closed %
            if(prospectiveStagesMap.get('Closed'+'_'+ls.Sales_Rep__c+'_'+ls.Active_Lead_Type__c+'_'+ls.Date__c) != null)
                ls.Closed__c = prospectiveStagesMap.get('Closed'+'_'+ls.Sales_Rep__c+'_'+ls.Active_Lead_Type__c+'_'+ls.Date__c);
            else
                ls.Closed__c = 0;
            // Retry %
            if(prospectiveStagesMap.get('Initial - to Retry'+'_'+ls.Sales_Rep__c+'_'+ls.Active_Lead_Type__c+'_'+ls.Date__c) != null)
                ls.Initial_to_Retry__c = prospectiveStagesMap.get('Initial - to Retry'+'_'+ls.Sales_Rep__c+'_'+ls.Active_Lead_Type__c+'_'+ls.Date__c);
            else
                ls.Initial_to_Retry__c = 0;
            //Overcome %
            if(prospectiveStagesMap.get('Overcome Objections'+'_'+ls.Sales_Rep__c+'_'+ls.Active_Lead_Type__c+'_'+ls.Date__c) != null)
                ls.Overcome_Objections__c = prospectiveStagesMap.get('Overcome Objections'+'_'+ls.Sales_Rep__c+'_'+ls.Active_Lead_Type__c+'_'+ls.Date__c);
            else
                ls.Overcome_Objections__c = 0;
            //Ready %
            if(prospectiveStagesMap.get('Ready to Close'+'_'+ls.Sales_Rep__c+'_'+ls.Active_Lead_Type__c+'_'+ls.Date__c) != null )
                ls.Ready_to_Close__c = prospectiveStagesMap.get('Ready to Close'+'_'+ls.Sales_Rep__c+'_'+ls.Active_Lead_Type__c+'_'+ls.Date__c);
            else
                ls.Ready_to_Close__c = 0;
            //Promised_to_Buy_Per__c
            if(prospectiveStagesMap.get('Promised To Buy'+'_'+ls.Sales_Rep__c+'_'+ls.Active_Lead_Type__c+'_'+ls.Date__c) != null)
                ls.Promised_to_Buy__c = prospectiveStagesMap.get('Promised To Buy'+'_'+ls.Sales_Rep__c+'_'+ls.Active_Lead_Type__c+'_'+ls.Date__c);
            else
                ls.Promised_to_Buy__c = 0;
            ls.Working__c=ls.Initial_to_Retry__c+ls.Overcome_Objections__c+ls.Promised_to_Buy__c+ls.Ready_to_Close__c;
            ls.Total_Leads_Sales_Rep_Lead_Type__c=TotalLeadsMap.get(ls.Sales_Rep__c+'_'+ls.Active_Lead_Type__c);           
            ls.No_of_Leads_Worked_Modified__c=TotalLeadsTodayMap.get(ls.Sales_Rep__c+'_'+ls.Active_Lead_Type__c+'_'+(ls.Date__c));
            leadshare_list.add(ls);
        }
        //  }     
        return leadshare_list;
    }
    global List<Leadshare__c> getNewLeadShares(List<Round_Robin_Client__c> p_round_robin_list){
        List<Leadshare__c> lead_shares_list=new List<Leadshare__c>();       
        //Create a Map for each Active_Lead_Type__c
        Map<String,List<Round_Robin_Client__c>> lead_type_map=new Map<String,List<Round_Robin_Client__c>>();
        for(Round_Robin_Client__c r:p_round_robin_list){
            //Add key if it is not exists
            if(!lead_type_map.containsKey(r.Active_Lead_Type__c+'_'+String.valueOf(r.Lastmodifieddate).split(' ')[0])){
                lead_type_map.put(r.Active_Lead_Type__c+'_'+String.valueOf(r.Lastmodifieddate).split(' ')[0],new List<Round_Robin_Client__c>());
            }
            //Add round robin records with same Active_Lead_Type__c
            if(lead_type_map.containsKey(r.Active_Lead_Type__c+'_'+String.valueOf(r.Lastmodifieddate).split(' ')[0])){               
                lead_type_map.get(r.Active_Lead_Type__c+'_'+String.valueOf(r.Lastmodifieddate).split(' ')[0]).add(r);
            }
        }
        System.debug('lead_type_map: '+lead_type_map);
        //create leadshare for each round robin record
        for(String ky:lead_type_map.keyset()){
            //Process each round robin
            for(Round_Robin_Client__c r:lead_type_map.get(ky)){
                Leadshare__c ls=new Leadshare__c();
                //ls.Name='Leadshare__'+System.today().format();                   
                if(r.Assigned__c!=null){
                    try{
                        ls.Round_robin__c=(r.Assigned__c/getSum(lead_type_map.get(ky)))*100;
                    }catch(Exception ex){
                        //division by zero error occured, initialize it to zero
                        ls.Round_robin__c=0;
                    }
                }
               
                ls.Date__c=system.today();
                ls.RoundRobin__c=r.Id;
                ls.Active_Lead_Type__c=r.Active_Lead_Type__c;
                ls.Sales_Rep__c=r.Originator__c;
                if(r.Skipped__c!=null)
                    ls.Skipped__c=String.valueOf(r.Skipped__c);
                ls.Total_Hits__c=r.Total_Hits__c;
                ls.Weight__c=r.Weight__c;
                ls.Workload__c=r.WorkLoad__c;
                ls.assigned__c=r.Assigned__c;
                //Add statistics from Originator
                /* 
ls.Contacted_Leads_for_Last__c=r.Originator__r.Contacted_Leads_for_Last__c;
ls.Calls_Duration_for_Last__c=r.Originator__r.Calls_Duration_for_Last__c;
ls.Calls_Number_for_Last__c=r.Originator__r.Calls_Number_for_Last__c;
ls.Invalid_Rate__c=r.Originator__r.Invalid_Rate__c;
ls.New_Leads_for_Last__c=r.Originator__r.New_Leads_for_Last__c;
ls.Lost_Rate__c=r.Originator__r.Lost_Rate__c;
ls.Closed_Rate__c=r.Originator__r.Closed_Rate__c;
ls.Calls_for_last_24h__c=r.Originator__r.Calls_for_last_24h__c;
ls.Time_on_Phone_for_Last_24h__c=r.Originator__r.Time_on_Phone_for_Last_24h__c;
ls.Initial_Contact__c=r.Originator__r.Initial_Contact__c;
ls.Initial_Contact_per__c=r.Originator__r.Initial_Contact_per__c;
ls.Overcome_Objections__c=r.Originator__r.Overcome_Objections__c;
ls.Overcome_Objections_per__c=r.Originator__r.Overcome_Objections_per__c;
ls.Promised_to_Buy__c=r.Originator__r.Promised_to_Buy__c;
ls.Promised_to_Buy_Per__c=r.Originator__r.Promised_to_Buy_Per__c;
ls.Ready_to_Close__c=r.Originator__r.Ready_to_Close__c;
ls.Ready_to_Close_per__c=r.Originator__r.Ready_to_Close_per__c;
ls.Closed__c=r.Originator__r.Closed__c;
ls.Closed_Per__c=r.Originator__r.Closed_Per__c;
ls.Lost__c=r.Originator__r.Lost__c;
ls.Lost_Per__c=r.Originator__r.Lost_Per__c;
ls.Save_for_Later__c=r.Originator__r.Save_for_Later__c;
ls.Save_for_Later_Per__c=r.Originator__r.Save_for_Later_Per__c;
ls.Invalid_Lead__c=r.Originator__r.Invalid_Lead__c;
ls.Invalid_Lead_Per__c=r.Originator__r.Invalid_Lead_Per__c;
ls.Closing_Rate_for_Last_30_Days__c=r.Originator__r.Closing_Rate_for_Last_30_Days__c;
ls.Closing_Rate_for_Last_60_Days__c=r.Originator__r.Closing_Rate_for_Last_60_Days__c;
ls.Closing_Rate_for_Last_90_Days__c=r.Originator__r.Closing_Rate_for_Last_90_Days__c;
ls.Closing_Rate_for_Last_120_Days__c=r.Originator__r.Closing_Rate_for_Last_120_Days__c;
ls.Closing_Rate_for_Last_180_Days__c=r.Originator__r.Closing_Rate_for_Last_180_Days__c;
ls.Total_of_Notes_for_Last_7_Days__c=r.Originator__r.Total_of_Notes_for_Last_7_Days__c;
ls.Total_of_Notes_for_Last_30_Days__c=r.Originator__r.Total_of_Notes_for_Last_30_Days__c;
ls.Total_of_E_Mails_Sent_for_Last_7_Days__c=r.Originator__r.Total_of_E_Mails_Sent_for_Last_7_Days__c;
ls.Total_of_E_Mails_Sent_for_Last_30_Days__c=r.Originator__r.Total_of_E_Mails_Sent_for_Last_30_Days__c;
ls.Total_of_SMS_Sent_for_Last_7_Days__c=r.Originator__r.Total_of_SMS_Sent_for_Last_7_Days__c;
ls.Total_of_SMS_Sent_for_Last_30_Days__c=r.Originator__r.Total_of_SMS_Sent_for_Last_30_Days__c;                 
ls.Average_of_Notes_Client_for_Last_7_Days__c=r.Originator__r.Average_of_Notes_per_Client_for_Last_7__c;
ls.Average_of_Notes_Client_for_Last_30_Days__c=r.Originator__r.Average_of_Notes_Client_for_Last_30_Days__c;
ls.Avg_of_E_Mails_Client_for_Last_7_Days__c=r.Originator__r.Avg_of_E_Mails_Client_for_Last_7_Days__c;
ls.Avg_of_E_Mails_Client_for_Last_30_Days__c=r.Originator__r.Avg_of_E_Mails_Client_for_Last_30_Days__c;
ls.Avg_of_SMS_Sent_Client_for_Last_7_Days__c=r.Originator__r.Avg_of_SMS_Sent_Client_for_Last_7_Days__c;
ls.Avg_of_SMS_Sent_Client_for_Last_30_Days__c=r.Originator__r.Avg_of_SMS_Sent_Client_for_Last_30_Days__c;
*/
                lead_shares_list.add(ls);               
            }           
        }       
        return lead_shares_list;
    }
   
    public Integer getSum(List<Round_Robin_Client__c> rrlist){
        Integer value=0;
        for(Round_Robin_Client__c r:rrlist){
            if(r.Total_Hits__c!=null)
                value+=Integer.valueOf(r.Total_Hits__c);
        }
        return value;
    }
}

Salesforce - Summarize Totals in Apex based on Date

global class RoundRobinSectors {
    Date today;
    Date yesterday;
    Date last7Days;
    Date last14Days;
    Date last30Days;
    Date firstDay_Currentweek;
    Date lastDay_Currentweek;
    Date firstDay_Lastweek;
    Date lastDay_Lastweek;
    Date firstDay_CurrentMonth;
    Date lastDay_CurrentMonth;
    Date firstDay_LastMonth;
    Date lastDay_LastMonth;
    Date LastTwoMonths;
    Date LastThreeMonths;
    Date LastSixMonths;
    Date Last12Months;
    global enum DateType {
        Today,Yesterday,CurrentWeek,Last7Days,Last14Days,Last30Days,LastWeek,CurrentMonth,LastMonth,TwoMonths,ThreeMonths,SixMonths,Last12Months
    }
    global void InitilizeDates(){
        Integer days=7;
        date myDate = date.today();
        today=myDate;
        yesterday=myDate.addDays(-1);
        last7Days=myDate.addDays(-7);
        last14Days=myDate.addDays(-14);
        last30Days=myDate.addDays(-30);
        firstDay_Currentweek = myDate.toStartofWeek();
        lastDay_Currentweek =   myDate.toStartofWeek().addDays(days);
        firstDay_Lastweek = myDate.addDays(-days).toStartofWeek();// need to check it
        lastDay_Lastweek =   myDate.addDays(-days).toStartofWeek().addDays(days);
        firstDay_CurrentMonth = myDate.toStartOfMonth();
        lastDay_CurrentMonth = firstDay_CurrentMonth.addDays(date.daysInMonth(myDate.year() , myDate.month()) - 1);
        firstDay_LastMonth = myDate.addMonths(-1).toStartOfMonth();
        lastDay_LastMonth = firstDay_LastMonth.addDays(date.daysInMonth(firstDay_LastMonth.year() , firstDay_LastMonth.month()));
        LastTwoMonths = myDate.addMonths(-2);
        LastThreeMonths = myDate.addMonths(-3);
        LastSixMonths = myDate.addMonths(-6);
        Last12Months = myDate.addMonths(-12);
    }
    global DateType IsCurrentDay(Date compareDate){
        system.debug('compareDate= '+compareDate);
        system.debug('today'+today);
        if(compareDate == today)
            return DateType.Today;
        return null;
    }
    global DateType IsYesterday(Date compareDate){
        if(compareDate == yesterday)
            return DateType.Yesterday;
        return null;
    }
    global DateType IsCurrentWeek(Date compareDate){
        if(compareDate > firstDay_Currentweek && compareDate <=lastDay_Currentweek)
            return DateType.CurrentWeek;
        return null;
    }
    global DateType IsLast7Days(Date compareDate){
        if(compareDate > last7Days && compareDate <=today)
            return DateType.Last7Days;
        return null;
    }
    global DateType IsLast14Days(Date compareDate){
        if(compareDate > last14Days && compareDate <=today)
            return DateType.Last14Days;
        return null;
    }
    global DateType IsLast30Days(Date compareDate){
        if(compareDate > last30Days && compareDate <=today)
            return DateType.Last30Days;
        return null;
    }
    global DateType IsLastWeek(Date compareDate){
        if(compareDate > firstDay_Lastweek && compareDate <=lastDay_Lastweek)
            return DateType.LastWeek;
        return null;
    }
 
    global DateType IsCurrentMonth(Date compareDate){
        /*system.debug('this is compareDate'+compareDate);
system.debug('this is firstDay_CurrentMonth'+firstDay_CurrentMonth);
system.debug('this is lastDay_CurrentMonth'+lastDay_CurrentMonth);*/
     
        if(compareDate >= firstDay_CurrentMonth && compareDate <=lastDay_CurrentMonth)
            return DateType.CurrentMonth;
        return null;
    }
 
    global DateType IsLastMonth(Date compareDate){
        system.debug('this is compareDate'+compareDate);
        system.debug('this is firstDay_LastMonth'+firstDay_LastMonth);
        system.debug('this is lastDay_LastMonth'+lastDay_LastMonth);
     
        if(compareDate >= firstDay_LastMonth && compareDate <=lastDay_LastMonth)
            return DateType.LastMonth;
        return null;
    }
 
    global DateType IsLastTwoMonths(Date compareDate){
        if(compareDate <= today && compareDate >=LastTwoMonths)
            return DateType.TwoMonths;
        return null;
    }
 
 
    global DateType IsLastThreeMonths(Date compareDate){
        if(compareDate <= today && compareDate >=LastThreeMonths)
            return DateType.ThreeMonths;
        return null;
    }
    global DateType IsLastSixMonths(Date compareDate){
        if(compareDate <= today && compareDate >=LastSixMonths)
            return DateType.SixMonths;
        return null;
    }
    global DateType IsLast12Months(Date compareDate){
        if(compareDate <= today && compareDate >=Last12Months)
            return DateType.Last12Months;
        return null;
    }
    public Decimal getSum(Decimal x,Decimal y){
        Decimal result=0;
        if(x==null)
            x=0;
        if(y==null)
            y=0;
        if(x!=null
           && y!=null){
               result=Math.abs(x+y);
           }
        return result;
    }
    public String getSum(String x,String y){
        Decimal result=0;     
        if(x==null)
            x='0';
        if(y==null)
            y='0';
        if(x!=null
           && y!=null){
               result=Math.abs(Decimal.valueOf(x)+Decimal.valueOf(y));
           }
        return String.valueOf(result);
    }
    public Decimal getDiv(Decimal x,Decimal y){
        Decimal result=0;
        if(x!=null
           && y!=null
           && y!=0){
               result=Math.abs(x/y);
           }
        return result;
    }
    public Decimal getDiv(String x,Decimal y){
        Decimal result=0;
        if(x!=null
           && y!=null
           && y!=0){
               result=Math.abs(Decimal.valueOf(x)/y);
           }
        return result;
    }
    public String getTwoDecimals(String x){
        String val='0.00';
        if(x.length()>5 && x.contains('.'))
            val=x.subString(0,5);
        else
            val=x;
        return val;
    }
    public Leadshare__c getSectorToday(List<Leadshare__c> p_leadsharelist){
        Leadshare__c leadshare;
        for(Leadshare__c s:p_leadsharelist){
            if(IsCurrentDay(s.Date__c)==DateType.Today){
                leadshare=s;
                break;
            }
        }
        return leadshare;
    }
    public Leadshare__c getSectorYesterday(List<Leadshare__c> p_leadsharelist){
        Leadshare__c leadshare;
        for(Leadshare__c s:p_leadsharelist){
            if(IsYesterday(s.Date__c)==DateType.Yesterday){
                leadshare=s;
                break;
            }
        }
        return leadshare;     
    }
    public Leadshare__c getSectorThisWeek(List<Leadshare__c> p_leadsharelist){
        Leadshare__c leadshare=new Leadshare__c();
        for(Leadshare__c ps:p_leadsharelist){
            if(IsCurrentWeek(ps.Date__c)==DateType.CurrentWeek){
                 leadshare.No_of_Leads_Called__c=getSum(leadshare.No_of_Leads_Called__c,ps.No_of_Leads_Called__c);
                 leadshare.Talk_Time__c=getSum(leadshare.Talk_Time__c,ps.Talk_Time__c);
                 leadshare.Inbound_Calls__c=getSum(leadshare.Inbound_Calls__c,ps.Inbound_Calls__c);
                 leadshare.Outbound_Calls__c=getSum(leadshare.Outbound_Calls__c,ps.Outbound_Calls__c);
                 leadshare.Invalid_Lead__c=getSum(leadshare.Invalid_Lead__c,ps.Invalid_Lead__c);
                 leadshare.Initial_Contact__c=getSum(leadshare.Initial_Contact__c,ps.Initial_Contact__c);
                 leadshare.Lost__c=getSum(leadshare.Lost__c,ps.Lost__c);
                 leadshare.Closed__c=getSum(leadshare.Closed__c,ps.Closed__c);
                 leadshare.No_of_Leads_Worked_Modified__c=getSum(leadshare.No_of_Leads_Worked_Modified__c,ps.No_of_Leads_Worked_Modified__c);
                 leadshare.Working__c=getSum(leadshare.Working__c,ps.Working__c);
                 leadshare.Total_Leads_Sales_Rep_Lead_Type__c=getSum(leadshare.Total_Leads_Sales_Rep_Lead_Type__c,ps.Total_Leads_Sales_Rep_Lead_Type__c);
            }
        }
        return leadshare;     
    }
    public Leadshare__c getSectorLast7Days(List<Leadshare__c> p_leadsharelist){
        Leadshare__c leadshare=new Leadshare__c();
        for(Leadshare__c ps:p_leadsharelist){
            if(IsLast7Days(ps.Date__c)==DateType.Last7Days){
                 leadshare.No_of_Leads_Called__c=getSum(leadshare.No_of_Leads_Called__c,ps.No_of_Leads_Called__c);
                 leadshare.Talk_Time__c=getSum(leadshare.Talk_Time__c,ps.Talk_Time__c);
                 leadshare.Inbound_Calls__c=getSum(leadshare.Inbound_Calls__c,ps.Inbound_Calls__c);
                 leadshare.Outbound_Calls__c=getSum(leadshare.Outbound_Calls__c,ps.Outbound_Calls__c);
                 leadshare.Invalid_Lead__c=getSum(leadshare.Invalid_Lead__c,ps.Invalid_Lead__c);
                 leadshare.Initial_Contact__c=getSum(leadshare.Initial_Contact__c,ps.Initial_Contact__c);
                 leadshare.Lost__c=getSum(leadshare.Lost__c,ps.Lost__c);
                 leadshare.Closed__c=getSum(leadshare.Closed__c,ps.Closed__c);
                 leadshare.No_of_Leads_Worked_Modified__c=getSum(leadshare.No_of_Leads_Worked_Modified__c,ps.No_of_Leads_Worked_Modified__c);
                 leadshare.Working__c=getSum(leadshare.Working__c,ps.Working__c);
                 leadshare.Total_Leads_Sales_Rep_Lead_Type__c=getSum(leadshare.Total_Leads_Sales_Rep_Lead_Type__c,ps.Total_Leads_Sales_Rep_Lead_Type__c);
            }
        }
        return leadshare;     
    }
    public Leadshare__c getSectorLast14Days(List<Leadshare__c> p_leadsharelist){
        Leadshare__c leadshare=new Leadshare__c();
        for(Leadshare__c ps:p_leadsharelist){
            if(IsLast14Days(ps.Date__c)==DateType.Last14Days){
                 leadshare.No_of_Leads_Called__c=getSum(leadshare.No_of_Leads_Called__c,ps.No_of_Leads_Called__c);
                 leadshare.Talk_Time__c=getSum(leadshare.Talk_Time__c,ps.Talk_Time__c);
                 leadshare.Inbound_Calls__c=getSum(leadshare.Inbound_Calls__c,ps.Inbound_Calls__c);
                 leadshare.Outbound_Calls__c=getSum(leadshare.Outbound_Calls__c,ps.Outbound_Calls__c);
                 leadshare.Invalid_Lead__c=getSum(leadshare.Invalid_Lead__c,ps.Invalid_Lead__c);
                 leadshare.Initial_Contact__c=getSum(leadshare.Initial_Contact__c,ps.Initial_Contact__c);
                 leadshare.Lost__c=getSum(leadshare.Lost__c,ps.Lost__c);
                 leadshare.Closed__c=getSum(leadshare.Closed__c,ps.Closed__c);
                 leadshare.No_of_Leads_Worked_Modified__c=getSum(leadshare.No_of_Leads_Worked_Modified__c,ps.No_of_Leads_Worked_Modified__c);
                 leadshare.Working__c=getSum(leadshare.Working__c,ps.Working__c);
                 leadshare.Total_Leads_Sales_Rep_Lead_Type__c=getSum(leadshare.Total_Leads_Sales_Rep_Lead_Type__c,ps.Total_Leads_Sales_Rep_Lead_Type__c);
            }
        }
        return leadshare;     
    }
    public Leadshare__c getSectorLast30Days(List<Leadshare__c> p_leadsharelist){
        Leadshare__c leadshare=new Leadshare__c();
        for(Leadshare__c ps:p_leadsharelist){
            if(IsLast30Days(ps.Date__c)==DateType.Last30Days){
                 leadshare.No_of_Leads_Called__c=getSum(leadshare.No_of_Leads_Called__c,ps.No_of_Leads_Called__c);
                 leadshare.Talk_Time__c=getSum(leadshare.Talk_Time__c,ps.Talk_Time__c);
                 leadshare.Inbound_Calls__c=getSum(leadshare.Inbound_Calls__c,ps.Inbound_Calls__c);
                 leadshare.Outbound_Calls__c=getSum(leadshare.Outbound_Calls__c,ps.Outbound_Calls__c);
                 leadshare.Invalid_Lead__c=getSum(leadshare.Invalid_Lead__c,ps.Invalid_Lead__c);
                 leadshare.Initial_Contact__c=getSum(leadshare.Initial_Contact__c,ps.Initial_Contact__c);
                 leadshare.Lost__c=getSum(leadshare.Lost__c,ps.Lost__c);
                 leadshare.Closed__c=getSum(leadshare.Closed__c,ps.Closed__c);
                 leadshare.No_of_Leads_Worked_Modified__c=getSum(leadshare.No_of_Leads_Worked_Modified__c,ps.No_of_Leads_Worked_Modified__c);
                 leadshare.Working__c=getSum(leadshare.Working__c,ps.Working__c);
                 leadshare.Total_Leads_Sales_Rep_Lead_Type__c=getSum(leadshare.Total_Leads_Sales_Rep_Lead_Type__c,ps.Total_Leads_Sales_Rep_Lead_Type__c);
            }
        }
        return leadshare;     
    }
    public Leadshare__c getSectorLastWeek(List<Leadshare__c> p_leadsharelist){
        Leadshare__c leadshare=new Leadshare__c();
        for(Leadshare__c ps:p_leadsharelist){
            if(IsLastWeek(ps.Date__c)==DateType.LastWeek){
                 leadshare.No_of_Leads_Called__c=getSum(leadshare.No_of_Leads_Called__c,ps.No_of_Leads_Called__c);
                 leadshare.Talk_Time__c=getSum(leadshare.Talk_Time__c,ps.Talk_Time__c);
                 leadshare.Inbound_Calls__c=getSum(leadshare.Inbound_Calls__c,ps.Inbound_Calls__c);
                 leadshare.Outbound_Calls__c=getSum(leadshare.Outbound_Calls__c,ps.Outbound_Calls__c);
                 leadshare.Invalid_Lead__c=getSum(leadshare.Invalid_Lead__c,ps.Invalid_Lead__c);
                 leadshare.Initial_Contact__c=getSum(leadshare.Initial_Contact__c,ps.Initial_Contact__c);
                 leadshare.Lost__c=getSum(leadshare.Lost__c,ps.Lost__c);
                 leadshare.Closed__c=getSum(leadshare.Closed__c,ps.Closed__c);
                 leadshare.No_of_Leads_Worked_Modified__c=getSum(leadshare.No_of_Leads_Worked_Modified__c,ps.No_of_Leads_Worked_Modified__c);
                 leadshare.Working__c=getSum(leadshare.Working__c,ps.Working__c);
                 leadshare.Total_Leads_Sales_Rep_Lead_Type__c=getSum(leadshare.Total_Leads_Sales_Rep_Lead_Type__c,ps.Total_Leads_Sales_Rep_Lead_Type__c);
            }
        }
        return leadshare;     
    }
    public Leadshare__c getSectorThisMonth(List<Leadshare__c> p_leadsharelist){
        Leadshare__c leadshare=new Leadshare__c();
        for(Leadshare__c ps:p_leadsharelist){
            if(IsCurrentMonth(ps.Date__c)==DateType.CurrentMonth){
                 leadshare.No_of_Leads_Called__c=getSum(leadshare.No_of_Leads_Called__c,ps.No_of_Leads_Called__c);
                 leadshare.Talk_Time__c=getSum(leadshare.Talk_Time__c,ps.Talk_Time__c);
                 leadshare.Inbound_Calls__c=getSum(leadshare.Inbound_Calls__c,ps.Inbound_Calls__c);
                 leadshare.Outbound_Calls__c=getSum(leadshare.Outbound_Calls__c,ps.Outbound_Calls__c);
                 leadshare.Invalid_Lead__c=getSum(leadshare.Invalid_Lead__c,ps.Invalid_Lead__c);
                 leadshare.Initial_Contact__c=getSum(leadshare.Initial_Contact__c,ps.Initial_Contact__c);
                 leadshare.Lost__c=getSum(leadshare.Lost__c,ps.Lost__c);
                 leadshare.Closed__c=getSum(leadshare.Closed__c,ps.Closed__c);
                 leadshare.No_of_Leads_Worked_Modified__c=getSum(leadshare.No_of_Leads_Worked_Modified__c,ps.No_of_Leads_Worked_Modified__c);
                 leadshare.Working__c=getSum(leadshare.Working__c,ps.Working__c);
                 leadshare.Total_Leads_Sales_Rep_Lead_Type__c=getSum(leadshare.Total_Leads_Sales_Rep_Lead_Type__c,ps.Total_Leads_Sales_Rep_Lead_Type__c);
            }
        }
        return leadshare;     
    }
    public Leadshare__c getSectorLastMonth(List<Leadshare__c> p_leadsharelist){
        Leadshare__c leadshare=new Leadshare__c();
        for(Leadshare__c ps:p_leadsharelist){
            if(IsLastMonth(ps.Date__c)==DateType.LastMonth){
                 leadshare.No_of_Leads_Called__c=getSum(leadshare.No_of_Leads_Called__c,ps.No_of_Leads_Called__c);
                 leadshare.Talk_Time__c=getSum(leadshare.Talk_Time__c,ps.Talk_Time__c);
                 leadshare.Inbound_Calls__c=getSum(leadshare.Inbound_Calls__c,ps.Inbound_Calls__c);
                 leadshare.Outbound_Calls__c=getSum(leadshare.Outbound_Calls__c,ps.Outbound_Calls__c);
                 leadshare.Invalid_Lead__c=getSum(leadshare.Invalid_Lead__c,ps.Invalid_Lead__c);
                 leadshare.Initial_Contact__c=getSum(leadshare.Initial_Contact__c,ps.Initial_Contact__c);
                 leadshare.Lost__c=getSum(leadshare.Lost__c,ps.Lost__c);
                 leadshare.Closed__c=getSum(leadshare.Closed__c,ps.Closed__c);
                 leadshare.No_of_Leads_Worked_Modified__c=getSum(leadshare.No_of_Leads_Worked_Modified__c,ps.No_of_Leads_Worked_Modified__c);
                 leadshare.Working__c=getSum(leadshare.Working__c,ps.Working__c);
                 leadshare.Total_Leads_Sales_Rep_Lead_Type__c=getSum(leadshare.Total_Leads_Sales_Rep_Lead_Type__c,ps.Total_Leads_Sales_Rep_Lead_Type__c);
            }
        }
        return leadshare;     
    }
}














/*
@date: 11/June/2018
@description: A batch class for Round robin improvements
*/
global class RoundRobinImprovementsBatch implements Database.Batchable<sObject>,Database.Stateful, Schedulable {   
    public List<Round_Robin_Client__c> round_robin_list;
    public RoundRobinSectors sector;
    global void scheduleMe(){ 
        String CRON=System.Label.RoundRobinImprovementsBatch_CRON;
        //Run the batch daily at mid night
        System.schedule('RoundRobinImprovementsBatch__'+DateTime.now(), CRON, new RoundRobinImprovementsBatch());   
    }
    global void execute(SchedulableContext sc){
        RoundRobinImprovementsBatch batch=new RoundRobinImprovementsBatch();
        ID batchprocessid=Database.executeBatch(batch);
    }
    //query RoundRobin records
    global Database.QueryLocator start(Database.BatchableContext BC) {
        round_robin_list=new List<Round_Robin_Client__c>();
        sector=new RoundRobinSectors();
        sector.InitilizeDates();
        //Query RoundRobin with recently created 90 Leadshares
        String query = 'SELECT '+ showFields('Round_Robin_Client__c')+       
            ', (SELECT '+showFields('Leadshare__c')+' FROM Leadshare__r ORDER BY lastmodifieddate DESC LIMIT 90) '+
            'FROM Round_Robin_Client__c '+
            'WHERE Active_Lead_Type__c!=NULL'+
            ' AND Status__c=\'Active\'';
        System.debug('query: '+query);
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Round_Robin_Client__c> scope) {
        //add all records of each batch
        round_robin_list.addAll(scope);
    } 
    global void finish(Database.BatchableContext BC) {
        List<Round_Robin_Client__c> rr_update_list=new List<Round_Robin_Client__c>();
        // Map<Id,List<Leadshare__c>> rrId_leadshare_map=new Map<Id,List<Leadshare__c>>();     
        for(Round_Robin_Client__c r:round_robin_list){
            //assigned yesterday - assigned current date
            r.Assigned_today__c=getAssigned(system.today()-1,system.today(),r.leadshare__r);
            //Assigned yesterday = day before yesterday - assigned yesterday
            r.Assigned_yesterday__c=getAssigned(system.today()-2,system.today()-1,r.leadshare__r);
            // assigned 7th day - assigned current date
            r.Assigned_last_7_days__c=getAssigned(system.today()-7,system.today(),r.leadshare__r);
            // assigned 14th day - assigned current date
            r.Assigned_last_14_days__c=getAssigned(system.today()-14,system.today(),r.leadshare__r);
            // assigned 30th day - assigned current date
            r.Assigned_last_30_days__c=getAssigned(system.today()-30,system.today(),r.leadshare__r);
            //update leadshare %
            r.Current_Per__c=getCurrentLeadPercent(system.today(),r.leadshare__r);
            r.Yesterday_per__c=getLeadPercent(System.today()-1,System.today(),r.leadshare__r);
            r.Last_7_Days__c=getLeadPercent(System.today()-7,System.today(),r.leadshare__r);
            r.Last_14_Days__c=getLeadPercent(System.today()-14,System.today(),r.leadshare__r);
            r.Last_30_Days__c=getLeadPercent(System.today()-30,System.today(),r.leadshare__r);           
            //Today
            LeadShare__c todayLS=sector.getSectorToday(r.leadshare__r);
            if(todayLS!=null){
              //  r.No_of_Leads_Called_Today__c=todayLS.No_of_Leads_Called__c;
             //   r.Talk_Time_Today__c=todayLS.Talk_Time__c;
             //   r.Inbound_Calls_Today__c=todayLS.Inbound_Calls__c;
             //   r.Outbound_Calls_Today__c=todayLS.Outbound_Calls__c;
                r.Invalid_Percent_Today__c=sector.getDiv(todayLS.Invalid_Lead__c,todayLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Initial_Contact_Uncalled_Per_Today__c=sector.getDiv(todayLS.Initial_Contact__c,todayLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Lost_Percent_Today__c=sector.getDiv(todayLS.Lost__c,todayLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Closed_Percent_Today__c=sector.getDiv(todayLS.Closed__c,todayLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Working_Today__c=sector.getDiv(todayLS.Working__c,todayLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.No_of_Leads_Worked_Modified_Today__c=todayLS.No_of_Leads_Worked_Modified__c;
            }
            else{               
             //   r.No_of_Leads_Called_Today__c=0;
             //   r.Talk_Time_Today__c='0';
             //   r.Inbound_Calls_Today__c=0;
             //   r.Outbound_Calls_Today__c=0;
                r.Invalid_Percent_Today__c=0;
                r.Initial_Contact_Uncalled_Per_Today__c=0;
                r.Lost_Percent_Today__c=0;
                r.Closed_Percent_Today__c=0;
                r.No_of_Leads_Worked_Modified_Today__c=0;
                r.Working_Today__c=0;
            }
            //Yesterday
            LeadShare__c yesterdayLS=sector.getSectorYesterday(r.leadshare__r);
            if(yesterdayLS!=null){
               // r.No_of_Leads_Called_Yesterday__c=yesterdayLS.No_of_Leads_Called__c;
              //  r.Talk_Time_Yesterday__c=yesterdayLS.Talk_Time__c;
               // r.Inbound_Calls_Yesterday__c=yesterdayLS.Inbound_Calls__c;
              //  r.Outbound_Calls_Yesterday__c=yesterdayLS.Outbound_Calls__c;
                r.Invalid_Per_Yesterday__c=sector.getDiv(yesterdayLS.Invalid_Lead__c,yesterdayLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Initial_Contact_Uncalled_Yesterday__c=sector.getDiv(yesterdayLS.Initial_Contact__c,yesterdayLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Lost_Per_Yesterday__c=sector.getDiv(yesterdayLS.Lost__c,yesterdayLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Closed_Per_Yesterday__c=sector.getDiv(yesterdayLS.Closed__c,yesterdayLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Working_Yesterday__c=sector.getDiv(yesterdayLS.Working__c,yesterdayLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.No_of_Leads_Worked_Modified_Yesterday__c=yesterdayLS.No_of_Leads_Worked_Modified__c;
            }
            else{
              //  r.No_of_Leads_Called_Yesterday__c=0;
              //  r.Talk_Time_Yesterday__c='0';
             //   r.Inbound_Calls_Yesterday__c=0;
             //   r.Outbound_Calls_Yesterday__c=0;
                r.Invalid_Per_Yesterday__c=0;
                r.Initial_Contact_Uncalled_Yesterday__c=0;
                r.Lost_Per_Yesterday__c=0;
                r.Closed_Per_Yesterday__c=0;
                r.Working_Yesterday__c=0;
                r.No_of_Leads_Worked_Modified_Yesterday__c=0;
            }                     
            //This Week
            LeadShare__c thisWeekLS=sector.getSectorThisWeek(r.leadshare__r);
            if(thisWeekLS!=null){
               // r.No_of_Leads_Called_ThisWeek__c=sector.getDiv(thisWeekLS.No_of_Leads_Called__c,thisWeekLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
              //  r.Talk_Time_ThisWeek__c=String.valueOf(sector.getDiv(thisWeekLS.Talk_Time__c,thisWeekLS.Total_Leads_Sales_Rep_Lead_Type__c)*100);
              //Take two decimal points
             //   r.Talk_Time_ThisWeek__c=sector.getTwoDecimals(r.Talk_Time_ThisWeek__c);
              //  r.Inbound_Calls_ThisWeek__c=sector.getDiv(thisWeekLS.Inbound_Calls__c,thisWeekLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
              //  r.Outbound_Calls_ThisWeek__c=sector.getDiv(thisWeekLS.Outbound_Calls__c,thisWeekLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Invalid_Per_ThisWeek__c=sector.getDiv(thisWeekLS.Invalid_Lead__c,thisWeekLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Initial_Contact_Uncalled_ThisWeek__c=sector.getDiv(thisWeekLS.Initial_Contact__c,thisWeekLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Lost_Per_ThisWeek__c=sector.getDiv(thisWeekLS.Lost__c,thisWeekLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Closed_Per_ThisWeek__c=sector.getDiv(thisWeekLS.Closed__c,thisWeekLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Working_ThisWeek__c=sector.getDiv(thisWeekLS.Working__c,thisWeekLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.No_of_Leads_Worked_Modified_ThisWeek__c=thisWeekLS.No_of_Leads_Worked_Modified__c;                   
            }
            else{
            //    r.No_of_Leads_Called_ThisWeek__c=0;
            //    r.Talk_Time_ThisWeek__c='0';
            //    r.Inbound_Calls_ThisWeek__c=0;
           //     r.Outbound_Calls_ThisWeek__c=0;
                r.Invalid_Per_ThisWeek__c=0;
                r.Initial_Contact_Uncalled_ThisWeek__c=0;
                r.Lost_Per_ThisWeek__c=0;
                r.Closed_Per_ThisWeek__c=0;
                r.Working_ThisWeek__c=0;
                r.No_of_Leads_Worked_Modified_ThisWeek__c=0;                                 
            }
            //Last 7 Days 
            LeadShare__c last7DaysLS=sector.getSectorLast7Days(r.leadshare__r);         
            if(last7DaysLS!=null){
               // r.No_of_Leads_Called_Last7Days__c=sector.getDiv(last7DaysLS.No_of_Leads_Called__c,last7DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
               // r.Talk_Time_Last7Days__c=String.valueOf(sector.getDiv(last7DaysLS.Talk_Time__c,last7DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100);
               // r.Talk_Time_Last7Days__c=sector.getTwoDecimals(r.Talk_Time_Last7Days__c);
              //  r.Inbound_Calls_Last7Days__c=sector.getDiv(last7DaysLS.Inbound_Calls__c,last7DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
              //  r.Outbound_Calls_Last7Days__c=sector.getDiv(last7DaysLS.Outbound_Calls__c,last7DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Invalid_Per_Last7Days__c=sector.getDiv(last7DaysLS.Invalid_Lead__c,last7DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Initial_Contact_Uncalled_Last7Days__c=sector.getDiv(last7DaysLS.Initial_Contact__c,last7DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Lost_Per_Last7Days__c=sector.getDiv(last7DaysLS.Lost__c,last7DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Closed_Per_Last7Days__c=sector.getDiv(last7DaysLS.Closed__c,last7DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Working_Last7Days__c=sector.getDiv(last7DaysLS.Working__c,last7DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.No_of_Leads_Worked_Modified_Last7Days__c=last7DaysLS.No_of_Leads_Worked_Modified__c;                   
            }
            else{
               // r.No_of_Leads_Called_Last7Days__c=0;
              //  r.Talk_Time_Last7Days__c='0';
              //  r.Inbound_Calls_Last7Days__c=0;
              //  r.Outbound_Calls_Last7Days__c=0;
                r.Invalid_Per_Last7Days__c=0;
                r.Initial_Contact_Uncalled_Last7Days__c=0;
                r.Lost_Per_Last7Days__c=0;
                r.Closed_Per_Last7Days__c=0;
                r.Working_Last7Days__c=0;
                r.No_of_Leads_Worked_Modified_Last7Days__c=0;                 
            }           
            //Last Week
            LeadShare__c lastWeekLS=sector.getSectorLastWeek(r.leadshare__r);
            if(lastWeekLS!=null){
              //  r.No_of_Leads_Called_LastWeek__c=sector.getDiv(lastWeekLS.No_of_Leads_Called__c,lastWeekLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
              //  r.Talk_Time_LastWeek__c=String.valueOf(sector.getDiv(lastWeekLS.Talk_Time__c,lastWeekLS.Total_Leads_Sales_Rep_Lead_Type__c)*100);
                //get only two decimals
              //  r.Talk_Time_LastWeek__c=sector.getTwoDecimals(r.Talk_Time_LastWeek__c);
              //  r.Inbound_Calls_LastWeek__c=sector.getDiv(lastWeekLS.Inbound_Calls__c,lastWeekLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
              //  r.Outbound_Calls_LastWeek__c=sector.getDiv(lastWeekLS.Outbound_Calls__c,lastWeekLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Invalid_Per_LastWeek__c=sector.getDiv(lastWeekLS.Invalid_Lead__c,lastWeekLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Initial_Contact_Uncalled_LastWeek__c=sector.getDiv(lastWeekLS.Initial_Contact__c,lastWeekLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Lost_Per_LastWeek__c=sector.getDiv(lastWeekLS.Lost__c,lastWeekLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Closed_Per_LastWeek__c=sector.getDiv(lastWeekLS.Closed__c,lastWeekLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.No_of_Leads_Worked_Modified_LastWeek__c=lastWeekLS.No_of_Leads_Worked_Modified__c;                   
                r.Working_LastWeek__c=sector.getDiv(lastWeekLS.Working__c,lastWeekLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
            }
            else{
              //  r.No_of_Leads_Called_LastWeek__c=0;
              //  r.Talk_Time_LastWeek__c='0';
              //  r.Inbound_Calls_LastWeek__c=0;
              //  r.Outbound_Calls_LastWeek__c=0;
                r.Invalid_Per_LastWeek__c=0;
                r.Initial_Contact_Uncalled_LastWeek__c=0;
                r.Lost_Per_LastWeek__c=0;
                r.Closed_Per_LastWeek__c=0;
                r.No_of_Leads_Worked_Modified_LastWeek__c=0;
                r.Working_LastWeek__c=0;
            }
            //Last 14 Days
            LeadShare__c last14DaysLS=sector.getSectorLast14Days(r.leadshare__r);
            if(last14DaysLS!=null){
              //  r.No_of_Leads_Called_Last14Days__c=sector.getDiv(last14DaysLS.No_of_Leads_Called__c,last14DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
              //  r.Talk_Time_Last14Days__c=String.valueOf(sector.getDiv(last14DaysLS.Talk_Time__c,last14DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100);
                //get only two decimals
             //   r.Talk_Time_Last14Days__c=sector.getTwoDecimals(r.Talk_Time_Last14Days__c);
             //   r.Inbound_Calls_Last14Days__c=sector.getDiv(last14DaysLS.Inbound_Calls__c,last14DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
             //   r.Outbound_Calls_Last14Days__c=sector.getDiv(last14DaysLS.Outbound_Calls__c,last14DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Invalid_Per_Last14Days__c=sector.getDiv(last14DaysLS.Invalid_Lead__c,last14DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Initial_Contact_Uncalled_Last14Days__c=sector.getDiv(last14DaysLS.Initial_Contact__c,last14DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Lost_Per_Last14Days__c=sector.getDiv(last14DaysLS.Lost__c,last14DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Closed_Per_Last14Days__c=sector.getDiv(last14DaysLS.Closed__c,last14DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.No_of_Leads_Worked_Modified_Last14Days__c=last14DaysLS.No_of_Leads_Worked_Modified__c;
                r.Working_Last14Days__c=sector.getDiv(last14DaysLS.Working__c,last14DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
            }
            else{
              //  r.No_of_Leads_Called_Last14Days__c=0;
              //  r.Talk_Time_Last14Days__c='0';
              //  r.Inbound_Calls_Last14Days__c=0;
             //   r.Outbound_Calls_Last14Days__c=0;
                r.Invalid_Per_Last14Days__c=0;
                r.Initial_Contact_Uncalled_Last14Days__c=0;
                r.Lost_Per_Last14Days__c=0;
                r.Closed_Per_Last14Days__c=0;
                r.No_of_Leads_Worked_Modified_Last14Days__c=0;
                r.Working_Last14Days__c=0;
            }           
            //This Month
            LeadShare__c thisMonthLS=sector.getSectorThisMonth(r.leadshare__r);
            if(thisMonthLS!=null){
               // r.No_of_Leads_Called_ThisMonth__c=sector.getDiv(thisMonthLS.No_of_Leads_Called__c,thisMonthLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
               // r.Talk_Time_ThisMonth__c=String.valueOf(sector.getDiv(thisMonthLS.Talk_Time__c,thisMonthLS.Total_Leads_Sales_Rep_Lead_Type__c)*100);
                //get Two Decimals
               // r.Talk_Time_ThisMonth__c=sector.getTwoDecimals(r.Talk_Time_ThisMonth__c);
               // r.Inbound_Calls_ThisMonth__c=sector.getDiv(thisMonthLS.Inbound_Calls__c,thisMonthLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
               // r.Outbound_Calls_ThisMonth__c=sector.getDiv(thisMonthLS.Outbound_Calls__c,thisMonthLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Invalid_ThisMonth__c=sector.getDiv(thisMonthLS.Invalid_Lead__c,thisMonthLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Initial_Contact_Uncalled_ThisMonth__c=sector.getDiv(thisMonthLS.Initial_Contact__c,thisMonthLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Lost_Per_ThisMonth__c=sector.getDiv(thisMonthLS.Lost__c,thisMonthLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Closed_Per_ThisMonth__c=sector.getDiv(thisMonthLS.Closed__c,thisMonthLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.No_of_Leads_Worked_Modified_ThisMonth__c=thisMonthLS.No_of_Leads_Worked_Modified__c;
                r.Working_ThisMonth__c=sector.getDiv(thisMonthLS.Working__c,thisMonthLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
            }
            else{
               // r.No_of_Leads_Called_ThisMonth__c=0;
               // r.Talk_Time_ThisMonth__c='0';
              //  r.Inbound_Calls_ThisMonth__c=0;
              //  r.Outbound_Calls_ThisMonth__c=0;
                r.Invalid_ThisMonth__c=0;
                r.Initial_Contact_Uncalled_ThisMonth__c=0;
                r.Lost_Per_ThisMonth__c=0;
                r.Closed_Per_ThisMonth__c=0;
                r.No_of_Leads_Worked_Modified_ThisMonth__c=0;
                r.Working_ThisMonth__c=0;
            }
            //Last Month
            Leadshare__c lastMonthLS=sector.getSectorLastMonth(r.leadshare__r);
            if(lastMonthLS!=null){
               // r.No_of_Leads_Called_LastMonth__c=sector.getDiv(lastMonthLS.No_of_Leads_Called__c,lastMonthLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
               // r.Talk_Time_LastMonth__c=String.valueOf(sector.getDiv(lastMonthLS.Talk_Time__c,lastMonthLS.Total_Leads_Sales_Rep_Lead_Type__c)*100);
                //get Two Decimals
               // r.Talk_Time_LastMonth__c=sector.getTwoDecimals(r.Talk_Time_LastMonth__c);
               // r.Inbound_Calls_LastMonth__c=sector.getDiv(lastMonthLS.Inbound_Calls__c,lastMonthLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
              //  r.Outbound_Calls_LastMonth__c=sector.getDiv(lastMonthLS.Outbound_Calls__c,lastMonthLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Invalid_Per_LastMonth__c=sector.getDiv(lastMonthLS.Invalid_Lead__c,lastMonthLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Initial_Contact_Uncalled_LastMonth__c=sector.getDiv(lastMonthLS.Initial_Contact__c,lastMonthLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Lost_Per_LastMonth__c=sector.getDiv(lastMonthLS.Lost__c,lastMonthLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Closed_Per_LastMonth__c=sector.getDiv(lastMonthLS.Closed__c,lastMonthLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.No_of_Leads_Worked_Modified_LastMonth__c=lastMonthLS.No_of_Leads_Worked_Modified__c;
                r.Working_LastMonth__c=sector.getDiv(lastMonthLS.Working__c,lastMonthLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
            }
            else{
               // r.No_of_Leads_Called_LastMonth__c=0;
               // r.Talk_Time_LastMonth__c='0';
               // r.Inbound_Calls_LastMonth__c=0;
              //  r.Outbound_Calls_LastMonth__c=0;
                r.Invalid_Per_LastMonth__c=0;
                r.Initial_Contact_Uncalled_LastMonth__c=0;
                r.Lost_Per_LastMonth__c=0;
                r.Closed_Per_LastMonth__c=0;
                r.No_of_Leads_Worked_Modified_LastMonth__c=0;
                r.Working_LastMonth__c=0;
            }
            //Last 30 Days
            LeadShare__c last30DaysLS=sector.getSectorLast30Days(r.leadshare__r);
            if(last30DaysLS!=null){
               // r.No_of_Leads_Called_Last30Days__c=sector.getDiv(last30DaysLS.No_of_Leads_Called__c,last30DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
               // r.TalkTime_Last30Days__c=String.valueOf(sector.getDiv(last30DaysLS.Talk_Time__c,last30DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100);
               // get Two Decimals
               //  r.TalkTime_Last30Days__c=sector.getTwoDecimals(r.TalkTime_Last30Days__c);
               // r.Inbound_Calls_Last30Days__c=sector.getDiv(last30DaysLS.Inbound_Calls__c,last30DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
               // r.Outbound_Calls_Last30Days__c=sector.getDiv(last30DaysLS.Outbound_Calls__c,last30DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Invalid_Per_Last30Days__c=sector.getDiv(last30DaysLS.Invalid_Lead__c,last30DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Initial_Contact_Uncalled_Last30Days__c=sector.getDiv(last30DaysLS.Initial_Contact__c,last30DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Lost_Per_Last30Days__c=sector.getDiv(last30DaysLS.Lost__c,last30DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.Closed_Per_Last30Days__c=sector.getDiv(last30DaysLS.Closed__c,last30DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
                r.No_of_Leads_Worked_Modified_Last30Days__c=last30DaysLS.No_of_Leads_Worked_Modified__c;                   
                r.Working_Last30Days__c=sector.getDiv(last30DaysLS.Working__c,last30DaysLS.Total_Leads_Sales_Rep_Lead_Type__c)*100;
            }
            else{
               // r.No_of_Leads_Called_Last30Days__c=0;
               // r.TalkTime_Last30Days__c='0';
               // r.Inbound_Calls_Last30Days__c=0;
               // r.Outbound_Calls_Last30Days__c=0;
                r.Invalid_Per_Last30Days__c=0;
                r.Initial_Contact_Uncalled_Last30Days__c=0;
                r.Lost_Per_Last30Days__c=0;
                r.Closed_Per_Last30Days__c=0;
                r.No_of_Leads_Worked_Modified_Last30Days__c=0;
                r.Working_Last30Days__c=0;                 
            }
            rr_update_list.add(r);
        }
        update rr_update_list;
    }
   
   
    public Decimal getAssigned(Date lastdate,Date currentdate,List<Leadshare__c> leadshares){
        Decimal current_val=0;
        Decimal last_val=0;
        Decimal result=0;
        List<Date> dateslist=new List<Date>();
        Map<date,Leadshare__c> datesmap=new Map<date,Leadshare__c>();
        //today and yesterday records available
        if(leadshares.size()>1){
            for(Leadshare__c ls:leadshares){
                if(ls.Date__c==currentdate){
                    current_val=ls.assigned__c;
                }
                else if(ls.Date__c==lastdate){
                    last_val=ls.assigned__c;
                }
                else if(current_val>0
                        && last_val>0){
                            break;
                        }
                dateslist.add(ls.Date__c);
                datesmap.put(ls.date__c,ls);
            }
        }
        dateslist.sort();
        if(last_val==0
           && leadshares.size()>1){
               last_val=datesmap.get(dateslist[0]).assigned__c;             
           }
        System.debug('('+lastdate+' - '+currentdate+')=>'+last_val+'-'+current_val);
        if(current_val!=null
           && last_val!=null){
               result=Math.abs(last_val-current_val);
           }
        return result;
    }
    public String showFields(String sobjectname) {
        //fields.clear();
        String fields='';
        system.debug('name' + sobjectname);
        Map <String, Schema.SObjectType> schemaMap = Schema.getGlobalDescribe();
        Map <String, Schema.SObjectField> fieldMap =  schemaMap.get(sobjectname).getDescribe().fields.getMap();
        for(Schema.SObjectField sfield : fieldMap.Values())
        {
            schema.describefieldresult dfield = sfield.getDescribe();
            // system.debug(dfield.getname()+'=>'+dfield.getLabel());
            fields+=dfield.getName()+',';
        }
        fields=fields.removeEnd(',');
        System.debug('fields: '+fields);
        return fields;
    }
   
    public Decimal getCurrentLeadPercent(Date currentdate,List<Leadshare__c> leadshares){
        Decimal current_val=0;
        for(Leadshare__c ls:leadshares){
            if(ls.Date__c==currentdate){
                current_val=ls.Round_robin__c;
                break;
            }
        }
        return current_val;
    }
    public Decimal getLeadPercent(Date lastdate,Date currentdate,List<Leadshare__c> leadshares){
        Decimal current_val=0;
        Decimal last_val=0;
        Decimal result=0;
        List<Date> dateslist=new List<Date>();
        Map<date,Leadshare__c> datesmap=new Map<date,Leadshare__c>();
        //today and yesterday records available
        if(leadshares.size()>1){
            for(Leadshare__c ls:leadshares){
                if(ls.Date__c==currentdate){
                    current_val=ls.Round_robin__c;
                }
                else if(ls.Date__c==lastdate){
                    last_val=ls.Round_robin__c;
                }
                else if(current_val>0
                        && last_val>0){
                            break;
                        }
                dateslist.add(ls.Date__c);
                datesmap.put(ls.date__c,ls);
            }
        }
        dateslist.sort();
        if(last_val==0
           && leadshares.size()>1){
               last_val=datesmap.get(dateslist[0]).Round_robin__c;             
           }
        System.debug('('+lastdate+' - '+currentdate+')=>'+last_val+'-'+current_val);
        if(current_val!=null
           && last_val!=null){
               result=Math.abs(last_val-current_val);
           }
        return result;
    }     
}




Sunday, 17 June 2018

Salesforce - Prevent dupilcate Records of a combination of values with a Trigger


trigger SameTypeBrandCheckTrigger on Marketing_Source__c (before insert,before update) {
    //Read custom settings
    Marketing_Source_Trigger_Switch__c ms_switch=Marketing_Source_Trigger_Switch__c.getValues('SameTypeBrandCheckTrigger');
    if(ms_switch!=null
       && ms_switch.isActive__c){
        if(trigger.isbefore){       
            if(trigger.isinsert){
                if(!Test.isRunningTest()){
                    SameTypeBrandCheckTriggerHelper.checkForSameTypeBrand(trigger.new);
                }
            }
            if(trigger.isupdate){
                for(Id mId:trigger.newMap.keyset()){
                    //check for a change in type or brand
                    if(trigger.oldMap.get(mId).Type__c!=trigger.newMap.get(mId).Type__c
                       || trigger.oldMap.get(mId).Brand__c!=trigger.newMap.get(mId).Brand__c){
                           if(!Test.isRunningTest()){ 
                               SameTypeBrandCheckTriggerHelper.checkForSameTypeBrand(trigger.new);
                           }
                       }
                }
            }   
        }
    }
}




Helper class:
=========


/*
    @date: 13/June/2018
    @description: Helper class for SameTypeBrandCheckTrigger to prevent duplicate marketing source records 
                  with same combination of Type and Brand
*/
public class SameTypeBrandCheckTriggerHelper {
    public static void checkForSameTypeBrand(List<Marketing_Source__c> mslist){
        Set<String> typeSet=new Set<String>();
        Set<String> brandSet=new Set<String>();
        //Add new type and brand
        for(Marketing_Source__c ms:mslist){
            typeSet.add(ms.Type__c);
            brandSet.add(ms.Brand__c);
        }
        //Prepare a map with same combination
        Map<Id,Marketing_Source__c> dupTypeBrandMap=new Map<Id,Marketing_source__c>([SELECT Id, Name, Type__c, Brand__c
                                                                                    FROM Marketing_Source__c 
                                                                                    WHERE Type__c IN:typeSet
                                                                                    AND Brand__c IN:brandSet]);
        //Check for duplicates
        for(Marketing_Source__c ms:mslist){
            Marketing_Source__c dupms=isExistsWithSameBrandAndType(ms,dupTypeBrandMap);
            if(dupms!=null){
                ms.addError('Same Type, Brand Combination already given to <a href=\'/'+dupms.Id+'\'>'+dupms.Name+'</a>',false);
            }
        }        
    }
    public static Marketing_Source__c isExistsWithSameBrandAndType(Marketing_Source__c p_ms,Map<Id,Marketing_Source__c> p_dupTypeBrandMap){
        Marketing_Source__c dupm=null;
        for(Id mId:p_dupTypeBrandMap.keySet()){
            //check for amatch
            if(p_ms.Type__c.equals(p_dupTypeBrandMap.get(mId).Type__c)
               && p_ms.Brand__c.equals(p_dupTypeBrandMap.get(mId).Brand__c)){
                dupm=p_dupTypeBrandMap.get(mId);
                break;
            }
        }
        return dupm;
    }
}