apr.blade.php 18 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']  : "00:00:00";
$logtimeto  =(isset($_GET['logtimeto']))? $_GET['logtimeto']:"23:59:59";
$logdate    =(isset($_GET['logdate']))  ? strtotime($_GET['logdate']." ".$logtime) : strtotime(date("Y-m-d")." ".$logtime);
$logdateto  =(isset($_GET['logdateto']))? strtotime($_GET['logdateto']." ".$logtimeto) : strtotime(date("Y-m-d")." ".$logtimeto);
$campaign   =(isset($_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));
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("Paused","AgentBriefing","TeamMeeting","QualityFeedback","LunchBreak","TeaBreak","UtilityBreak","FloorAnnouncements","DownTime");
//$reporthead=array_merge(array("Agent Name","Emp ID","Date","OB Call","IB Call","Cons Call","Conf","Login Time","OB Talk","Avg Talk Time","Ring Time","Avg Ring Time","Wrap Time","Avg Wrap Time","Total Productive Time","Total Handling Time","Avg Handling Time","Idle Time","INT Time","Dial Time","Cons Time","Agent Break","Lunch","Tea","Emergency","Briefing","Quality","Login","Headset Unplugged","Manual","Grand Total","Score","Actual Login Time","Team Leader","OJT/Non OJT","Layer","Status","Week","Month","Date","Net Login Duraion","Preview Time","Wrap Active Time","Day"),$breaks);
$reporthead=array("Agent Name","Emp ID","Date","OB Call","IB Call","Cons Call","Conf","Login Time","OB Talk","Avg Talk Time","Ring Time","Avg Ring Time","Wrap Time","Avg Wrap Time","Total Productive Time","Total Handling Time","Avg Handling Time","Idle Time","INT Time","Dial Time","Cons Time","Agent Break","Lunch","Tea","Emergency","Briefing","Quality","Login","Headset Unplugged","Manual","Grand Total","Score","Actual Login Time","Team Leader","OJT/Non OJT","Layer","Status","Week","Month","Date","Net Login Duraion","Preview Time","Wrap Active Time","Day");
$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();

	$logdatefrom = $logdate;
	while ($logdatefrom <= $logdateto) {
		foreach($allusers as $tuser)
		{
			$uidlist[]=$tuser->id;
			
			//$reportarray[date("Y-m-d", $logdatefrom)][$aline->user_id]=array("#"=>$i++,"Agent Name"=>$tuser->telecaller,"Emp ID"=>$tuser->username,"Date"=>date("Y-m-d", $logdatefrom),"Team Leader"=>$tuser->sepervisor);
			$reportarray[date("Y-m-d", $logdatefrom)][$tuser->id]=array("Agent Name"=>$tuser->telecaller,"Emp ID"=>$tuser->username,"Date"=>date("d M Y", $logdatefrom),"OB Call","IB Call","Cons Call","Conf","Login Time","OB Talk","Avg Talk Time","Ring Time","Avg Ring Time","Wrap Time","Avg Wrap Time","Total Productive Time","Total Handling Time","Avg Handling Time","Idle Time","INT Time","Dial Time","Cons Time","Agent Break","Lunch","Tea","Emergency","Briefing","Quality","Login","Headset Unplugged","Manual","Grand Total","Score","Actual Login Time","Team Leader"=>$tuser->sepervisor,"OJT/Non OJT"=>"","Layer"=>"Agent","Status","Week"=>"Week " . weekOfMonth($logdatefrom),"Month"=>date("F", $logdatefrom),"Date"=>date("d M Y", $logdatefrom),"Net Login Duraion","Preview Time","Wrap Active Time","Day"=>date("D", $logdatefrom));
		}
		$logdatefrom = strtotime("+1 day", $logdatefrom);
	}
	$alist=$alist->whereIn('user_id',$uidlist);

	/*$alist=$alist->where(function ($query) use($roclientstr,$uidlist,$didlinesstr){
	 $query->orWhereIn('client',$roclientstr)
	 ->orWhereIn('did',$didlinesstr);
	 });*/
	$userlog=$userlog->whereIn('user_id',$uidlist);
}
else {
	$allusers=$allusers->get();
	$logdatefrom = $logdate;
	while ($logdatefrom <= $logdateto) {
		foreach($allusers as $tuser)
		{			
			//$reportarray[date("Y-m-d", $logdatefrom)][$tuser->id]=array("#"=>$i++,"Agent Name"=>$tuser->telecaller,"Emp ID"=>$tuser->username,"Date"=>date("d M Y", $logdatefrom),"Team Leader"=>$tuser->sepervisor);
			$reportarray[date("Y-m-d", $logdatefrom)][$tuser->id]=array("Agent Name"=>$tuser->telecaller,"Emp ID"=>$tuser->username,"Date"=>date("d M Y", $logdatefrom),"OB Call","IB Call","Cons Call","Conf","Login Time","OB Talk","Avg Talk Time","Ring Time","Avg Ring Time","Wrap Time","Avg Wrap Time","Total Productive Time","Total Handling Time","Avg Handling Time","Idle Time","INT Time","Dial Time","Cons Time","Agent Break","Total Login hour","Lunch","Tea","Emergency","Briefing","Quality","Login","Headset Unplugged","Manual","Grand Total","Score","Actual Login Time","Team Leader"=>$tuser->sepervisor,"OJT/Non OJT"=>"","Layer"=>"Agent","Status","Week"=>"Week " . weekOfMonth($logdatefrom),"Month"=>date("F", $logdatefrom),"Date"=>date("d M Y", $logdatefrom),"Net Login Duraion","Preview Time","Wrap Active Time","Day"=>date("D", $logdatefrom));
		}
	$logdatefrom = strtotime("+1 day", $logdatefrom);
	}
}
//echo '<pre>';print_r($reportarray);
$alist=$alist->get();
$userlog=$userlog->get();
$prev_close = 0;
$allcall=$obcall=$ibcall=$mancall=0;
$ibtalktime=$obtalktime=$mantalktime=0;
foreach($alist as $aline)
{
	if($prev_user != $aline->user_id || $prev_close <= $aline->ts_Wait)
	{
		$userid=$aline->user_id;
		$type = $aline->type;
		
		switch($type){
			case 'Inbound':
				$ibtalktime=$aline->talkSec+$aline->recstartSec+$aline->recendSec;
				$ibcall++;
				break;
			case 'Manual':
				$mantalktime=$aline->talkSec+$aline->recstartSec+$aline->recendSec;
				$mancall++;
				break;
			default:
				$obtalktime=$aline->talkSec+$aline->recstartSec+$aline->recendSec;
				$obcall++;
		}
		$allcall++;
		
		$talktime=$aline->talkSec+$aline->recstartSec+$aline->recendSec;
		$totaltime=$aline->callSec+$talktime+$aline->dispoSec;		
		
		$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["OB Call"] = $obcall;
		$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["IB Call"] = $ibcall;
		$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["Cons Call"] = '';
		$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["Conf"] = '';
		
		// OB Talk
		$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["OB Talk"]+=$obtalktime/1000;
		$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["Avg Talk Time"]+=($obtalktime/$obcall)/1000;
		
		// Ring
		$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["Ring Time"]+=$aline->callSec/1000;
		$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["Avg Ring Time"]+=($aline->callSec/$allcall)/1000;
		
		// Hold
		/* $reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["Hold Time"]+=$aline->callSec/1000;
		$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["Avg Hold Time"]+=($aline->callSec/$allcall)/1000; */
		
		// Wrap
		$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["Wrap Time"]+=$aline->dispoSec/1000;
		$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["Avg Wrap Time"]+=($aline->dispoSec/$allcall)/1000;
		
		// Total Productive Time  Ring time is pending to minus from totaltime
		$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["Total Productive Time"]+=($totaltime-($aline->callSec))/1000;
		
		// Total Handling Time
		$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["Total Handling Time"]+=($totaltime-($aline->talkSec+$aline->dispoSec))/1000;
		$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["Avg Handling Time"]+=(($totaltime-($aline->talkSec+$aline->dispoSec))/$allcall)/1000;
		
		// Wrap Active time		
		$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["Wrap Active Time"]+=$aline->dispoSec/1000;

		$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["oncall"]+=$totaltime/1000;
		//$reportarray[$userid]["Idle Time"]+=$aline->waitSec/1000;
		//$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["Hold Time"]+=$aline->callSec/1000;
		//$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["Talk Time"]+=$talktime/1000;
		//$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["Wrap Time"]+=$aline->dispoSec/1000;
		
		// Manual
		$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["Manual"]+=$mantalktime/1000;
	}
	$reportarray[date("Y-m-d", strtotime($aline->created_at))][$userid]["Total dialouts"]++;
	$prev_close = $aline->ts_Close;//-ts_Wait
	$prev_user = $aline->user_id;//-ts_Wait
}

$userLogin=array();
foreach($userlog as $ulog)
{
	if($ulog->durationsec != 0) {
		$userLogin[$ulog->user_id]['duration'] += $ulog->durationsec;
		$userLogin[$ulog->user_id]['start'][] = strtotime($ulog->startdate . ' ' . $ulog->starttime);
		$userLogin[$ulog->user_id]['end'][] = strtotime($ulog->enddate . ' ' . $ulog->endtime);
	}
	else {
		if(preg_match_all('/(\d+(\.\d+)?)/', $ulog->data, $numbers)) {
			$starttime = strtotime($ulog->startdate.' '.$ulog->starttime);
			$endtime   = round(end($numbers[0])/1000);
			$userLogin[$ulog->user_id]['duration'] += ($endtime-$starttime);
			$userLogin[$ulog->user_id]['start'][] = $starttime;
			$userLogin[$ulog->user_id]['end'][] = $endtime;
		}
	}
	$data=json_decode($ulog->data,true);
	$prets=strtotime($ulog->startdate." ".$ulog->starttime)*1000;
	$previous="Paused-Paused";
	
	foreach($data as $sdata)
	{
		$pts=$sdata['ts'];
		if(isset($sdata['states']))
		{
			foreach($sdata['states'] as $ts=>$states)
			{
				$previous = str_replace('Paused-', '', $previous);
				if(!in_array($previous,$reporthead)) $previous = 'Paused';
				
				$reportarray[date("Y-m-d", strtotime($ulog->created_at))][$ulog->user_id][$previous]+=round($ts-$prets,2)/1000;
				$prets=$ts;
				$previous=$states[0].'-'.$states[1];
			}
			$previous = str_replace('Paused-', '', $previous);
			$reportarray[date("Y-m-d", strtotime($ulog->created_at))][$ulog->user_id][$previous]+=round($pts-$prets,2)/1000;
		}
	}
}

$logdatefrom = $logdate;
while ($logdatefrom <= $logdateto) {	
	if(count($userLogin)) foreach ($userLogin as $userid => $value)
	{
		$break_time=0;
		foreach ($breaks as $break) {
			$break_time+=$reportarray[date("Y-m-d", $logdatefrom)][$userid][$break];
		}
		// Agent Break
		$reportarray[date("Y-m-d", $logdatefrom)][$userid]["Agent Break"]=$break_time;
		$reportarray[date("Y-m-d", $logdatefrom)][$userid]["Grand Total"]=$value['duration'];
		
		$reportarray[date("Y-m-d", $logdatefrom)][$userid]["Net Login Duraion"]=$value['duration'];
		
		$reportarray[date("Y-m-d", $logdatefrom)][$userid]["Signin"]=date("Y-m-d H:i:s", min($value['start'])-$timeoffset);
		$reportarray[date("Y-m-d", $logdatefrom)][$userid]["Signout"]=date("Y-m-d H:i:s", max($value['end'])-$timeoffset);
		$reportarray[date("Y-m-d", $logdatefrom)][$userid]["Login Time"]=$value['duration'];
		$reportarray[date("Y-m-d", $logdatefrom)][$userid]["TOS"]=$value['duration']-$break_time;
		$reportarray[date("Y-m-d", $logdatefrom)][$userid]["Actual Login Time"]=$reportarray[date("Y-m-d", $logdatefrom)][$userid]["TOS"];
		$reportarray[date("Y-m-d", $logdatefrom)][$userid]["Idle Time"]=$reportarray[date("Y-m-d", $logdatefrom)][$userid]["TOS"]-$reportarray[date("Y-m-d", $logdatefrom)][$userid]['oncall'];
	}
	$logdatefrom = strtotime("+1 day", $logdatefrom);
}
$highestColumn = sizeof($reporthead);
if(count($reportarray)) {
	$outhead="<tr>";$outstr="";
	for ($head = 0; $head < $highestColumn; $head++){
		$outhead.="<td>".$reporthead[$head]."</td>";
	}
	$outhead.="</tr>";
	$utotalarr = array("Emp ID"=>'Total');
	
	$logdatefrom = $logdate;
	while ($logdatefrom <= $logdateto) {
		foreach($reportarray[date("Y-m-d", $logdatefrom)] as $uid=>$uarr)
		{
			$outstr.="<tr>";
			for ($head = 0; $head < $highestColumn; $head++){
				if($head < 7 || ($head > 32 && $head < 40) || $head == 43) {
					$data_str = $uarr[$reporthead[$head]];
				}
				else {
					$data_str = secToDuration(round($uarr[$reporthead[$head]]));
					$utotalarr[$reporthead[$head]] += $uarr[$reporthead[$head]];
				}
				$outstr.="<td>".$data_str."</td>";
			}
			$outstr.="</tr>";
		}
		$logdatefrom = strtotime("+1 day", $logdatefrom);
	}
	$outstr.="<tr>";
	for ($head = 0; $head < $highestColumn; $head++)
	{
		if($head < 8) {
			$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]);
	}
	$logdatefrom = $logdate;
	while ($logdatefrom <= $logdateto) {
		foreach($reportarray[date("Y-m-d", $logdatefrom)] as $uid=>$uarr)
		{
			$row = $baseRow++;
			$col = 0;
	
			for ($head = 0; $head < $highestColumn; $head++){
				$excelval = ($head < 8) ? $uarr[$reporthead[$head]] : secToDuration(round($uarr[$reporthead[$head]]));
				$colstr=PHPExcel_Cell::stringFromColumnIndex($head);
				$objPHPExcel->getActiveSheet()->setCellValue($colstr.$row, $excelval);
			}
		}
		$logdatefrom = strtotime("+1 day", $logdatefrom);
	}
	$row++;
	for ($head = 0; $head < $highestColumn; $head++){
		$excelval = ($head < 8) ? $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="APR.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);
}
function weekOfMonth($date) {
	//Get the first day of the month.
	$firstOfMonth = strtotime(date("Y-m-01", $date));
	//Apply above formula.
	return intval(date("W", $date)) - intval(date("W", $firstOfMonth)) + 1;
}
?>
<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;">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("");' /> 
        To <input size=10 id='modto' name='modto' type='text' value='<?php echo date("Y-m-d",$logdateto); ?>' onchange='statusLogReloadFun("");' />    
</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()+'&logdateto='+$("#modto").val();
}
function statusLogReloadFun(sortby)
{
    var sortstr='';if(sortby!="")sortstr="&sort="+sortby
    var searchStr = dataString();
    doAjax('dialer/apr?'+searchStr+sortstr,'','rightmainreportdiv','ajax_dialer_reports','singlethis','GET');
}
function dlAgentlogXls()
{
    var searchStr = dataString();
    window.open('dialer/apr?dllogxls=1&'+searchStr);
    return false;
}
</script>