Thursday, 5 July 2018

Salesforce - Formula for taking only Date part from Lastmodifieddate





IF(BEGINS(TEXT(TIMEVALUE(LastModifiedDate)), "04:"),
DATEVALUE(LastModifiedDate+1),
DATEVALUE(LastModifiedDate)
)

Monday, 2 July 2018

jqgrid - drag and drop table rows from bottom to top and save data with filters in salesforce


PrioritizeProjects.vfp
===============

<apex:page controller="PrioritizeProjectsController" showHeader="false" sidebar="false" >
    <html>
        <head>
            <!-- The jQuery library is a prerequisite for all jqSuite products -->
            <script type="text/ecmascript" src="https://www.guriddo.net/demo/js/jquery.min.js"></script>
            <!-- This is the Javascript file of jQuery UI --> 
                <script type="text/ecmascript" src="https://www.guriddo.net/demo/js/jquery-ui.min.js"></script>
            <!-- This is the Javascript file of jqGrid --> 
            <script type="text/ecmascript" src="https://www.guriddo.net/demo/js/trirand/jquery.jqGrid.min.js"></script>
            <!-- This is the localization file of the grid controlling messages, labels, etc.
            <!-- We support more than 40 localizations -->
                <script type="text/ecmascript" src="https://www.guriddo.net/demo/js/trirand/i18n/grid.locale-en.js"></script>
            <!-- A link to a jQuery UI ThemeRoller theme, more than 22 built-in and many more custom -->
            <link rel="stylesheet" type="text/css" media="screen" href="https://www.guriddo.net/demo/css/jquery-ui.css" />
            <!-- The link to the CSS that the grid needs -->
            <link rel="stylesheet" type="text/css" media="screen" href="https://www.guriddo.net/demo/css/trirand/ui.jqgrid.css" />
            <meta charset="utf-8" />
            <title>Prioritize Projects</title>
            <script type="text/javascript">
            var getProjectsList = '{!$RemoteAction.PrioritizeProjectsController.getProjectsList}';
            var saveProjectsList = '{!$RemoteAction.PrioritizeProjectsController.saveProjectsList}';         
            </script>
            <script src="{!$Resource.PrioritizeProjectsControllerJS}" type="text/javascript"></script>         
            </head>
            <script> var previousOnload = window.onload; window.onload = function() { if (previousOnload) { previousOnload(); } showDataInJqGrid(); } </script>
            <body>
                <div style="margin:3%">               
                    <div id="response" style="font-size: 16px;width: 300px;font-family: monospace; font-stretch: expanded" />
                 
                    <apex:form >
                        Project:
                        <apex:selectList id="pr" multiselect="false" size="1" onchange="doFilter();">
                            <apex:selectOptions value="{!projectStatuslist}"></apex:selectOptions>
                        </apex:selectList>&nbsp;&nbsp;
                        Worker:
                        <apex:selectList id="wr" size="1" multiselect="false" onchange="doFilter();">
                            <apex:selectOptions value="{!workerslist}"></apex:selectOptions>
                        </apex:selectList>
                    </apex:form>
                    <br />
                    <br />
                 
                        <table id="grid1"></table>
                        <div id="pgrid1"></div>                 
                        <br />         
                        <input type="button" value="Save Updated Order Of Priorities" onClick="savePriorities();" />
                 
                    <br />
                </div>
             
            </body>
        </html>
    </apex:page>




PrioritizeProjectsControllerJS.js
=======================
var gridData;
var obj;

function showDataInJqGrid(){
    var accName = '';
    //document.getElementById("query").value;
    console.log('accName: '+accName);
    //get filters
    var project=document.getElementById('j_id0:j_id2:pr').value;
    var worker=document.getElementById('j_id0:j_id2:wr').value;
   // placeData('All','All');
    placeData(project,worker);
}
function placeData(project,worker) { 
    var jsonString;
    Visualforce.remoting.Manager.invokeAction(
        getProjectsList,
        project,
        worker,
        function (result, event) {
            try{
                if(event.type == 'exception'){
                    alert(event.message);
                } else{     
                    jsonString = result;     
                    showProjectsList(jsonString);
                  //  gridData = JSON.stringify(jsonString);
                }
            }catch(err){
                console.log('Exception: '+err.stack);
            }
        },
        {escape: true}
    );
}
function showProjectsList(jsonString) {
    var cnames=jsonString.cnames;
    var cmodel=jsonString.cmodels;
    var data=jsonString.datalist;
    gridData=data;
    console.log('data: '+JSON.stringify(data)); 
 
    jQuery("#grid1").jqGrid({     
        height: 160,
        colNames: cnames,
        colModel: cmodel,
        caption: 'Prioritize Projects',
        pager: '#pgrid1'
    }); 
 
    for (var i = 0; i <= data.length; i++) {
        jQuery("#grid1").jqGrid('addRowData',i + 1, data[i]);
    }
 
  //  jQuery("#grid1").jqGrid('gridDnD',{connectWith:'#grid1'});

  // move rows to anywhere
 $('#grid1').jqGrid('sortableRows', {
      cancel:".jqgrow.notsortable"
});

    $(window).on("resize", function () {
          // alert('test window');
        var $grid = $("#grid1"),
            newWidth = $grid.closest(".ui-jqgrid").parent().width();
        $grid.jqGrid("setGridWidth", newWidth, true);
    });
 
}



$(document).ready(function(){
 
 
});

function doFilter(){
    var project=document.getElementById('j_id0:j_id2:pr').value;
    var worker=document.getElementById('j_id0:j_id2:wr').value;
    //alert('Project: '+project+'\nWorker: '+worker);
    //clear grid data
    jQuery("#grid1").jqGrid("clearGridData");
    placeData(project,worker);
    //Reload Grid
    $('#grid1').trigger( 'reloadGrid' );
}

function savePriorities(){
    console.log('savePriorities success');
     var datafromgrid = $('#grid1').jqGrid('getRowData');
    console.log('datafromgrid: '+JSON.stringify(datafromgrid));
    //update priorities
    for (var i = 0; i < datafromgrid.length; i++) {
        console.log('Name: '+datafromgrid[i].Name);
        datafromgrid[i].Current_Priority__c=(i+1)
    } 
    console.log('updated data: '+JSON.stringify(datafromgrid));   
    var project=document.getElementById('j_id0:j_id2:pr').value;
    var worker=document.getElementById('j_id0:j_id2:wr').value;
    //save data
    Visualforce.remoting.Manager.invokeAction(
        saveProjectsList,
        JSON.stringify(datafromgrid),
        project,
        worker,
        function (result, event) {
            try{
                if(event.type == 'exception'){
                    alert(event.message);
                } else{
    //clear grid data
    jQuery("#grid1").jqGrid("clearGridData");
                    //show updatd projects
    placeData(project,worker);
                }
            }catch(err){
                console.log('Exception: '+err.stack);
            }
        },
        {escape: true}
    );
}





PrioritizeProjectsController.cls
======================
global class PrioritizeProjectsController {
    global String selectedProject{get;set;}
    public PrioritizeProjectsController() {
selectedProject='';     
    } 
    @RemoteAction
    global static ProjectWrapper getProjectsList(String p_project,String p_worker){
       // system.debug('Inside method: '+accName);
       // accName = '%'+ accName+'%';
        List<Project_Management__c> projects = new List<Project_Management__c>();
        ProjectWrapper pw=new ProjectWrapper();
        String query='SELECT Id,Name, Current_Priority__c, Parent_Project__r.Name,Project_Number__c,Requester__r.Name, Worker__r.Name, '+
            'Status__c, Status_Date__c, Completion_Proof__c,'+
                    'Description__c,Type__c,Initial_Priority_Placement__c, Date_Stamp_Assigned__c, '+
                    'Project_Age_Days__c,Createddate,Reject_Reason__c '+                                                 
                    'FROM Project_Management__c'+
            ' Where Status__c=:p_project AND Worker__c=:p_worker';
       /* if(!p_project.equals('All')
           && !p_worker.equals('All')){
             query+=' Where Status__c=:p_project AND Worker__c=:p_worker';
        }
        else if(!p_project.equals('All')
                && p_worker.equals('All')){
            query+=' Where Status__c=:p_project';
        }
        else if(p_project.equals('All')
                && !p_worker.equals('All')){
            query+=' Where Worker__c=:p_worker';
        }*/
        query+=' ORDER BY Current_Priority__c ASC';
        System.debug('query: '+query);
        projects = Database.query(query);
        System.debug('Projects: '+projects);     
        projects.add(new Project_Management__c(Name='ETC'));
        // WHERE status__c IN: {'Working','Backlog'}];
        List<String> cnamelist=new List<String>();
        cnamelist.add('Current_Priority__c');
        cnamelist.add('Name');
        cnamelist.add('Parent_Project__r.Name');
        cnamelist.add('Project_Number__c');
        cnamelist.add('Type__c');
        cnamelist.add('Requester__r.Name');
        cnamelist.add('CreatedDate');
        cnamelist.add('Status__c');
        cnamelist.add('Status_Date__c');   
        cnamelist.add('Worker__r.Name');
        cnamelist.add('Completion_Proof__c');
        cnamelist.add('Reject_Reason__c');
        List<ColModelWrapper> cmodelslist=new List<ColModelWrapper>();
        List<String> newcnamelist=new List<String>();
        for(String c:cnamelist){
            cmodelslist.add(new ColModelWrapper(c,c,95));
            if(c.contains('__r.Name'))
                c=c.replace('__r.Name','');
            if(c.contains('__c'))
                c=c.replace('__c','');
            if(c.contains('_'))
                c=c.replace('_',' ');
            if(c.equals('Name'))
                c='Project Name';
            newcnamelist.add(c);
        }
        pw.datalist=projects;
        pw.cnames=newcnamelist;
        pw.cmodels=cmodelslist;
       // System.debug('projects: '+pw);
        return pw;
    } 
    global class ProjectWrapper{
        global List<String> cnames;
        global List<ColModelWrapper> cmodels;
        global List<Project_Management__c> datalist;
        global ProjectWrapper(){}     
    }
    global class ColModelWrapper{
        global String name;
        global String index;
        global Integer width;
        global ColModelWrapper(String p_name,String p_index,Integer p_width){
            name=p_name;
            index=p_index;
            width=p_width;
        }
    }
    public List<SelectOption> getworkerslist() {
        List<SelectOption> options = new List<SelectOption>();
       // options.add(new SelectOption('All','All'));
        Map<String,String> workersMap=new Map<String,String>();
        for(Project_management__c pm:[SELECT Worker__c, Worker__r.Name
                                      FROM Project_management__c]){
                                          if(!workersMap.containsKey(pm.worker__c)){
                                              options.add(new SelectOption(pm.Worker__c,pm.Worker__r.Name));
                                              workersMap.put(pm.Worker__c,pm.Worker__r.Name);
                                          }
                                      }
        return options;
    }
    public List<SelectOption> getprojectStatusList(){
         List<SelectOption> options = new List<SelectOption>();
        // options.add(new SelectOption('All','All'));
         Map<String,String> workersMap=new Map<String,String>();
        for(Project_management__c pm:[SELECT Worker__c, Worker__r.Name ,Status__c
                                      FROM Project_management__c]){
                                          if(!workersMap.containsKey(pm.Status__c)){
                                              options.add(new SelectOption(pm.Status__c,pm.Status__c));
                                              workersMap.put(pm.Status__c,pm.Status__c);
                                          }
                                      }
        return options;
    }
     @RemoteAction
    global static void saveProjectsList(String p_projects,String p_project,String p_worker){
    Map<String,Id> projectNumberIdMap=new Map<String,Id>();
        for(Project_Management__c pm:[select Id,Project_Number__c
                                      From Project_Management__c
                                     WHERE Status__c=:p_project
                                      AND Worker__c=:p_worker]){
                                        projectNumberIdMap.put(pm.Project_Number__c,pm.Id);
                                      }
       List<Project_management__c> projects=(List<Project_Management__c>)JSON.deserialize(p_projects, List<Project_Management__c>.class);
       List<Project_management__c> processed=new List<Project_management__c>();
        System.debug('projectNumberIdMap: '+projectNumberIdMap);
        // Remove last index ETC     
        for(Project_management__c pm:projects){
            if(!pm.name.equals('ETC')){
                pm.Id=projectNumberIdMap.get(pm.Project_Number__c);
                processed.add(pm);
            }
        }
        update processed;
    } 
}








Downloads:

https://drive.google.com/open?id=1AsXMVp0ygBFnjrKfTpy1R__xhVGgpK0W

https://drive.google.com/open?id=1VmJqcO8XmfqZJVzMj0tM4XO4h-wbwde9


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;
    }     
}