demo_agentperformance.php 12.6 KB
<?php
use App\Models\CRMCall;
use App\Models\CRMCallArchive;
use App\Models\User;
use App\Models\UserLog;
use App\Jobs\KHRMSLib;

$wakka = new KHRMSLib();
$dashboarduser=Auth::user();
$timeoffset = $dashboarduser->timezone; //-330; //$dashboarduser->timezone;
$timeoffset = $timeoffset*60;

$logtime    =(isset($_GET['logtime']))  ? $_GET['logtime']  :"09:00:00";
$logtimeto  =(isset($_GET['logtimeto']))? $_GET['logtimeto']:"20:00:00";

$logdate    =(isset($_GET['logdate']))  ? strtotime($_GET['logdate']." ".$logtime.":00:00")
                                        : strtotime(date("Y-m-d")." 09:00:00");
$logdateto  =(isset($_GET['logdateto']))? strtotime($_GET['logdateto']." ".$logtimeto.":00:00")
                                        : strtotime(date("Y-m-d")." 20:00:00");
$campaign   =(isset($_GET['campaign']) && $_GET['campaign'] != '')  ? $_GET['campaign']  : "All";

$alist=CRMCallArchive::where('user_id','!=',0)->where('created_at','>=',date("Y-m-d H:i:s",$logdate+$timeoffset))->where('created_at','<=',date("Y-m-d H:i:s",$logdateto+$timeoffset));
$alist->orderBy('user_id', 'ASC')->orderBy('ts_Close', 'ASC');

// $userlog=UserLog::where('created_at','>=',date("Y-m-d H:i:s",$logdate+$timeoffset))->where('created_at','<=',date("Y-m-d H:i:s",$logdateto+$timeoffset));
$userlog = new UserLog();
$userlog_report_data=$userlog->getAgentPerformanceReportUserLog($logdate, $logdateto, $timeoffset);

if($campaign != 'All') $alist->where('client','=',$campaign);

$userarr=array();
$allusers = DB::table('users as u1')->leftjoin('users AS u2', 'u2.username', '=', 'u1.supervisor')
    ->select('u1.id','u1.username','u1.fullname AS telecaller', 'u2.fullname AS sepervisor')
    ->where('u1.status','=','Active');

$roclientstr=array();$didlinesstr=array();
if($dashboarduser->exten!="")$didlinesstr[]=$dashboarduser->exten;
$oclientlst=$wakka->clientsReadAccess(); sort($oclientlst); $oclientlst[0] = 'All';

if(!empty($oclientlst))foreach($oclientlst as $tclnt)if($tclnt!="")
{
    $roclientstr[]="$tclnt";
    
    $mastersdata=$wakka->getCompanyMaster($tclnt);
    if(!empty($mastersdata["DialerDID"]))$didlinesstr[]=$mastersdata["DialerDID"];
}

$breaks=array("AgentBriefing","TeamMeeting","QualityFeedback","LunchBreak","TeaBreak","UtilityBreak","FloorAnnouncements","DownTime");
$reporthead=array("#","Telecaller","Calls","Contacts","RPC","PTP","Preview","Call","Talk","Wrap","Idle","Breaks","Duration");
$reportarray=array();

$i=1;
if($dashboarduser->usertype != 'Admin')
{
    $uidlist=array($dashboarduser->id);
    $allusers=$allusers->where(function ($query)  use($dashboarduser) {
        $query->where('u1.supervisor','=',$dashboarduser->username)
        ->orWhere('u1.lteam2','=',$dashboarduser->username)
        ->orWhere('u1.lteam','=',$dashboarduser->username);
    })->get();

    foreach($allusers as $tuser)
    { 
        $uidlist[]=$tuser->id;
        $reportarray[$tuser->id]=array("#"=>$i++,"Telecaller"=>$tuser->telecaller,"Calls"=>0,"Contacts"=>0,"RPC"=>0,"PTP"=>0);
    }
    $reportarray[$dashboarduser->id]=array("#"=>$i++,"Telecaller"=>$dashboarduser->fullname,"Calls"=>0,"Contacts"=>0,"RPC"=>0,"PTP"=>0);

    $alist=$alist->whereIn('user_id',$uidlist);

    $userlog=$userlog->whereIn('user_id',$uidlist);     
}else{
    $allusers=$allusers->get();
    foreach($allusers as $tuser)
    {
        $reportarray[$tuser->id]=array("#"=>$i++,"Telecaller"=>$tuser->telecaller,"Calls"=>0,"Contacts"=>0,"RPC"=>0,"PTP"=>0);
    }
}

$alist=$alist->get();
$user_id = '';
$total_staff_time = $total_attend_time = 0;
$Wait_Time= $Call_Time= $Talk_Time= $Disp_Time= 0;
$total_paused_time = 0;
foreach($alist as $aline)
{
    $userid=$aline->user_id;

    $reportarray[$userid]["User"] = $userid;
    $reportarray[$userid]["Calls"]++;
    if($aline->userstatus == 'Contacted') {
        $reportarray[$userid]["Contacts"]++;
    }
    if($aline->resultCode == 'PTP') {
        $reportarray[$userid]["PTP"]++;
    }
    if($aline->resultCode == 'BP' || $aline->resultCode == 'CB' || $aline->resultCode == 'CEREP' || $aline->resultCode == 'OT' || $aline->resultCode == 'PD' || $aline->resultCode == 'PTP' || $aline->resultCode == 'PV' || $aline->resultCode == 'RTP' || $aline->resultCode == 'SETLD') {
        $reportarray[$userid]["RPC"]++;
    }
        $ts_Wait = round(($aline->ts_Call - $aline->ts_Wait)/1000,2);
        $ts_Call = round(($aline->ts_Talk - $aline->ts_Call)/1000,2);
        $ts_Talk = round(($aline->ts_Dispo - $aline->ts_Talk)/1000,2);
        $ts_Dispo = round(($aline->ts_Close - $aline->ts_Dispo)/1000,2);

        $totaltime= $ts_Call + $ts_Talk + $ts_Dispo;

        $reportarray[$userid]["oncall"]+=$totaltime;
        $reportarray[$userid]["Call"]+=$ts_Call;
        $reportarray[$userid]["Talk"]+=$ts_Talk;
        $reportarray[$userid]["Wrap"]+=$ts_Dispo;
    
}

foreach($userlog_report_data as $userlog)
{         

    $userid=$userlog->user_id;
    if($user_id != $userlog->user_id) {
        $user_id = $userlog->user_id;
        $total_staff_time = $total_attend_time = 0;
        $Wait_Time= $Call_Time= $Talk_Time= $Disp_Time= 0;
        $total_paused_time = 0;
    }

    $user_logs_id = $userlog->user_logs_id;
    $total_staff_time = $total_staff_time + $userlog->total_staff_time;
    $total_attend_time = $total_attend_time + $userlog->total_attend_time;
    $userlogg = new UserLog();
    $total_paused_time = $total_paused_time + $userlogg->getTotalPauseTimeOFUserLogsColumnData($user_logs_id);
   
    $reportarray[$userid]["Duration"]=$total_attend_time;
    $reportarray[$userid]["Breaks"]=$total_paused_time;
    $reportarray[$userid]["Idle"]=$total_attend_time-$total_staff_time;
    $reportarray[$userid]["Preview"]=$total_attend_time-($total_paused_time+$reportarray[$userid]["Idle"]+$reportarray[$userid]["oncall"]);
}
$checkhead = array_merge($reporthead, $breaks);

$highestColumn = sizeof($reporthead);
if(count($reportarray)) {
    $outhead="<tr>";$outstr="";
    for ($head = 0; $head < $highestColumn; $head++){
        if($reporthead[$head] == '#') {
            $mode_str = "<a onclick='displayMode(".'"summation"'.");return false;' href='#'><i class='fa fa-plus-square-o'></i></a> / <a onclick='displayMode(".'"percent"'.");return false;' href='#'>%</a>";
            $outhead.="<td>".$mode_str."</td>";
        }
        else {
            $outhead.="<td>".$reporthead[$head]."</td>";
        }
    }
    $outhead.="</tr>";
    $utotalarr = array("Telecaller"=>'Total');
    
    foreach($reportarray as $uid=>$uarr)
    {
        $outstr.="<tr>";
        for ($head = 0; $head < $highestColumn; $head++){
            if($head < 2) {
                $data_str = $uarr[$reporthead[$head]];
            }
            elseif($head < 6) {
                $data_str = $uarr[$reporthead[$head]];
                $utotalarr[$reporthead[$head]] += $uarr[$reporthead[$head]];          
            }
            else {
                $data_str = secToDuration(round($uarr[$reporthead[$head]]));
                $utotalarr[$reporthead[$head]] += $uarr[$reporthead[$head]];          
            }
            $outstr.="<td>".$data_str."</td>";
        }
        $outstr.="</tr>";
    }
    $outstr.="<tr>";
    for ($head = 0; $head < $highestColumn; $head++)
    {
        if($head < 6) {
            $data_str = $utotalarr[$reporthead[$head]];
        }
        else {
            $data_str = secToDuration($utotalarr[$reporthead[$head]]);  
        }
        $outstr.="<td>".$data_str."</td>";
    }
    $outstr.="</tr>";
}
else
{
    $outhead.="<tr><td>No Records Found.</td></tr>";
}  

if(Input::has("dllogxls"))
{
    include_once(app_path().'/lib/phpexcel/PHPExcel.php');
    
    $inputFileType = "Excel5";
    $objReader = PHPExcel_IOFactory::createReader($inputFileType);
    $objPHPExcel = $objReader->load("assets/extras/blank.xls");
    $baseRow = 2;


    $highestColumn = sizeof($reporthead);
    for ($head = 0; $head < $highestColumn; $head++){
        $colstr=PHPExcel_Cell::stringFromColumnIndex($head);
        $objPHPExcel->getActiveSheet()->setCellValue($colstr."1", $reporthead[$head]);
    }

    foreach($reportarray as $uid=>$uarr)
    {
        $row = $baseRow++;
        $col = 0;
        
        for ($head = 0; $head < $highestColumn; $head++){
            $excelval = ($head < 6) ? $uarr[$reporthead[$head]] : secToDuration(round($uarr[$reporthead[$head]]));
            $colstr=PHPExcel_Cell::stringFromColumnIndex($head); 
            $objPHPExcel->getActiveSheet()->setCellValue($colstr.$row, $excelval);
        }
    }

    $row++;
    for ($head = 0; $head < $highestColumn; $head++){
        $excelval = ($head < 6) ? $utotalarr[$reporthead[$head]] : secToDuration(round($utotalarr[$reporthead[$head]]));
        $colstr=PHPExcel_Cell::stringFromColumnIndex($head);
        $objPHPExcel->getActiveSheet()->setCellValue($colstr.$row, $excelval);
    }

    header('Content-Type: application/vnd.ms-excel');
    header('Content-Disposition: attachment;filename="AgentPerformance.xls"');
    header('Cache-Control: max-age=0');

    $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, $inputFileType);
    $objWriter->save('php://output');
    
    return ;
}

function secToDuration($sec) {
    return sprintf("%02d%s%02d%s%02d", floor($sec/3600), ':', ($sec/60)%60, ':', $sec%60);
}
?>

<style>#logtable.td{vertical-align:top;}#logtable.tr{height:28px;overflow-y:hidden;}</style>

<div class=innerAll>
<h4 style="float:left;width:50%;margin:10px 0;">Demo Agent Performance Report</h4>
<div style="float:right;width:50%">
<button class='pull-right btn btn-sm btn-default' onclick='dlAgentlogXls();return false;' title='Download'><i class='fa fa-download'></i> Download</button>
</div>
<div style="clear:both"></div>
<hr style="margin-bottom: 5px;">
<div>
    Search <input id=filter name="filter" type="text" style="border:1px solid #efefef; padding: 2px 10px;">&nbsp;&nbsp;
    Date: From <input size=10 id='modfrom' name='modfrom' type='text' value='<?php echo date("Y-m-d",$logdate); ?>' onchange='statusLogReloadFun("");' /> 
        <select id="modtime" style="border:1px solid #efefef;" onchange='statusLogReloadFun("");'>
        <?php 
            foreach (range(0,23) as $hour) {
                $selected = ($hour == $logtime) ? "selected" : "";
                echo "<option value='$hour' $selected>".str_pad($hour, 2, "0", STR_PAD_LEFT) . ":00</option>";
            }
        ?></select>
        To <input size=10 id='modto' name='modto' type='text' value='<?php echo date("Y-m-d",$logdateto); ?>' onchange='statusLogReloadFun("");' />
        <select id="modtimeto" style="border:1px solid #efefef;" onchange='statusLogReloadFun("");'>
        <?php 
            foreach (range(0,23) as $hour) {
                $selected = ($hour == $logtimeto) ? "selected" : "";
                echo "<option value='$hour' $selected>".str_pad($hour, 2, "0", STR_PAD_LEFT) . ":00</option>";
            }
        ?></select>
</div>

<div style="clear:both"></div>
<hr style="margin:5px;">

<div style="overflow: auto; margin-top: 10px;">
    <table id=logtable class='footable table table-striped table-bordered table-white table-primary footable-loaded' style='font-size:12px; margin:0; border:1px solid #BBB;'>
        <thead><?php echo $outhead; ?></thead>
        <?php echo $outstr; ?>
    </table>
</div>

<div id=dialoglog></div>
</div>

<script>
$(document).ready(function() {
    if(!$('#dialoglog').hasClass('ui-dialog-content'))
    {
        $('#dialoglog').dialog({
            autoOpen: false,
            width: '70%',
            buttons: {
                "Ok": function() { 
                    $(this).dialog("close"); 
                }, 
                "Cancel": function() { 
                    $(this).dialog("close"); 
                } 
            }
        });
    }

    waitKeyUpRun("filter",function() { filter2(document.getElementById('filter'), 'logtable') },"2000");
    $('#modfrom').datepicker({dateFormat: 'yy-mm-dd',inline: true,changeYear: true,selectOtherMonths: true,yearRange: '<?php echo (date('Y')-70).":".(date('Y')+5); ?>'});
    $('#modto').datepicker({dateFormat: 'yy-mm-dd',inline: true,changeYear: true,selectOtherMonths: true,yearRange: '<?php echo (date('Y')-70).":".(date('Y')+5); ?>'});
});

function dataString()
{
    return 'logdate='+$("#modfrom").val()+'&logtime='+$("#modtime").val()+'&logdateto='+$("#modto").val()+'&logtimeto='+$("#modtimeto").val()+'&campaign=All';//+$("#campaign").val();
}
function statusLogReloadFun(sortby)
{
    var sortstr='';if(sortby!="")sortstr="&sort="+sortby
    var searchStr = dataString();
    doAjax('dialer/demo_agentperformance?'+searchStr+sortstr,'','rightmainreportdiv','ajax_dialer_reports','singlethis','GET');
}
function dlAgentlogXls()
{
    var searchStr = dataString();
    window.open('dialer/demo_agentperformance?dllogxls=1&'+searchStr);
    return false;
}
</script>