CreateCall.php 8.31 KB
<?php namespace App\Console\Commands;

use Illuminate\Console\Command;
//use Mail;
use DB;
use Config;

use App\Models\User;
use App\Models\Accesslog;

use App\Models\CRMCall;
use Schema;
use PDO;
use App\Models\Notification;
use App\Jobs\KHRMSLib;

use Input;
use Log;
use App\Models\Sipid;
use App\Models\Kqueue;
use App\Models\Dialline;
use App\Models\Session;
use App\Models\Cutoff;

use Illuminate\Database\Schema\Blueprint;

class CreateCall extends Command {

	/**
	 * The console command name.
	 *
	 * @var string
	 */
	protected $signature = 'CreateCall';

	/**
	 * The console command description.
	 *
	 * @var string
	 */
	protected $description = 'Create Pedictive Call If any User is Free';

	/**
	 * Execute the console command.
	 *
	 * @return mixed
	 */
	public function handle()
	{
		while(true)
		{
			usleep(1000000);
			$this->runPredictive();
		}
	}

	public function runPredictive()
	{

		try {
			$this->updatePrepareColumn();
			$usrArrs        = $this->getActiveUsersCampaignWise("with");
			$availChannel   = $this->getActualAvailChannelCount();

			if(count($usrArrs)){

				//Log::useFiles(storage_path()."/logs/predictive_".date("Y_m_d").".log");
				//Log::info($usrArrs);

				//Log::useFiles(storage_path()."/logs/predictive_".date("Y_m_d").".log");
				//Log::info("Channel=".$availChannel);

				foreach ($usrArrs as $client => $usrArr) {
					//Log::useFiles(storage_path()."/logs/predictive_".date("Y_m_d").".log");
					//Log::info("campaign=".$client);

					$acalls = $this->getCreateCallCount($client, count($usrArr));

					$acalls = min($acalls, $availChannel);

					//Log::useFiles(storage_path()."/logs/predictive_".date("Y_m_d").".log");
					//Log::info("CallCount=".$acalls);

					$this->CreateCall($client, $acalls);
				}
			}
		} catch (Exception $e) {
			Log::useFiles(storage_path()."/logs/predictive_".date("Y_m_d").".log");
			Log::error($e);
			continue;
		}
	}

	public function updatePrepareColumn()
	{
		$allClientUsrIdArr = array();
		$updatedUserIdArr = array();
		$currentTime = strtotime(date("Y-m-d H:i:s"));

		$clientWiseUserIdArr = $this->getActiveUsersCampaignWise("without");

		if(count($clientWiseUserIdArr)) {
			//Log::useFiles(storage_path()."/logs/predictive_".date("Y_m_d").".log");
			//Log::info("updatePrepareColumn");Log::info($clientWiseUserIdArr);

			foreach ($clientWiseUserIdArr as $client => $usrIdArr) {
			$allClientUsrIdArr = array_merge($allClientUsrIdArr, $usrIdArr);
			}

			$usersTimeArr = Cutoff::whereIn('user_id', $allClientUsrIdArr)->get();

			foreach ($usersTimeArr as $userTimeArr) {
				$cutOffTime = strtotime($userTimeArr->hangup_time) + ($userTimeArr->avg_dispo - $userTimeArr->avg_ring);

					if($cutOffTime < $currentTime)
					{
						$updatedUserIdArr[] = $userTimeArr->user_id;
					}
			}

			if(count($updatedUserIdArr)) {
				//Log::useFiles(storage_path()."/logs/predictive_".date("Y_m_d").".log");
				//Log::info("updatedUserIdArr");Log::info($updatedUserIdArr);
			}

			Sipid::whereIn('user', $updatedUserIdArr)->update(['prepare_call'=>1]);
		}
	}

	public function getActiveUsersCampaignWise($checkPrepareCol)
	{
		$campaignWiseUsrs = array();
		$prepareUsrIds    = array();

		$loggedInSips = Sipid::where('server','=',env('app_ip'))->where("user", "!=", 0)->where("status","=","1");
		if($checkPrepareCol=="with"){
			$loggedInSips = $loggedInSips->where("prepare_call","=","1");
		}
		elseif($checkPrepareCol=="without"){
				$loggedInSips = $loggedInSips->where("patched","=","0");
			}

		$loggedInSips = $loggedInSips->groupBy('user')->get();

		if(count($loggedInSips)){

			foreach ($loggedInSips as $loggedInSip) {
				$prepareUsrIds[] = $loggedInSip->user;
			}

			//TODO: Change Dialmode Value in the column Of User Table (Ready to Predictive)
			$usersLoggedIn = User::whereIn('id', $prepareUsrIds);
			if($checkPrepareCol=="without")$usersLoggedIn = $usersLoggedIn->where('current_dialmode', '=', 'Predictive');
			$usersLoggedIn = $usersLoggedIn->select('id','sel_campaign')->get();

			foreach ($usersLoggedIn as $userLoggedIn) {
				$campaignWiseUsrs[$userLoggedIn->sel_campaign][] = $userLoggedIn->id;
			}
		}
		return $campaignWiseUsrs;
	}

	public function getActualAvailChannelCount()
	{
		$cnt = 0;
		$allChanlCnt = $this->getSpanCount();

		$diallineVal = Dialline::where('server','=', env('app_ip'))->where("status","=","Free")->where("dialstr","!=","")->where("enabled","=","1")->select('dialstr')->first();

//TODO: When SIP and Dahdi both are active
		if(count($diallineVal)){
			if(stristr($diallineVal->dialstr,"Dahdi")){
				$dialedCnt = $this->getActualDahdiDialedCallCount();

				$cnt = $allChanlCnt - $dialedCnt;
			}
			elseif(stristr($diallineVal->dialstr,"GATEWAY")){
				$dialedCnt = $this->getActualSipDialedCallCount();

				$cnt = $allChanlCnt - $dialedCnt;
			}
		}

		return $cnt;
	}

	public function getActualSipDialedCallCount()
	{
		$allChnnlArr = array();
		$dialstr     = "Dial(SIP/GATEWAY/";
		$chnlCnt     = 0;

		exec("/usr/sbin/asterisk -rx 'core show channels'",$allChnnls);

		foreach($allChnnls as $allChnnl){
		//$allChnnlArr[] = explode(" ", preg_replace('!\s+!', ' ', $allChnnl) );
			if(stristr($allChnnl, $dialstr)){
               $chnlCnt++;
        	}
		}

		return $chnlCnt;
	}

	public function getActualDahdiDialedCallCount()
	{
		$allChnnlArr = array();
		$dialstr     = "ACTIVE";
		$status      = "RED";
		$chnlCnt     = 0;

		exec("/usr/sbin/asterisk -rx 'service dahdi status'",$allChnnls);

		foreach($allChnnls as $allChnnl){
		//$allChnnlArr[] = explode(" ", preg_replace('!\s+!', ' ', $allChnnl) );
			if(stristr($allChnnl, $status)){
               Break;
        	}

			if(stristr($allChnnl, $dialstr)){
               $chnlCnt++;
        	}
		}

		return $chnlCnt;
	}

//TODO: Generate Client File To Take All Parameteres Of Campaigns
	public function getCreateCallCount($client, $usrCnt)
	{
		$wakka = new KHRMSLib();
		$mastersdata=$wakka->getCompanyMaster($client);

		$ratio          = $mastersdata["autodialercampaign"];
		$dialedCallCnt  = $this->getDialedCallCount($client);

		return ($usrCnt*$ratio) - $dialedCallCnt;
	}

	public function getDialedCallCount($client)
	{
		$cnt = Dialline::whereIn("status", ["Auto","AutoCall"])->where("conf","=","")->where("regexstr","=",$client)->count();

		return $cnt;
	}

	public function CreateCall($client, $acalls)
	{
		if($acalls>0)
		{
			for($i=0;$i<$acalls;$i++)
			{
				$this->useChannelToDial($client);
			}
		}
	}

	public function useChannelToDial($client)
	{
		$dialline=Dialline::where('server','=', env('app_ip'))->where("status","=","Free")->where("enabled","=","1");
		
		//TODO::Need To Code Dspan Logic as per discussion
		//if($dspan!="")$dialline=$dialline->where('dspan','=',$dspan)->where('id','<=','30');
		$dialline=$dialline->orderBy('updated_at','ASC')->first();

		if(!empty($dialline))
		{
			$this->createCrmCall($client, $dialline);
		}

		return;
	}

	public function createCrmCall($client, $dialline)
	{
		//TODO: Need to check whether callerid is required or not (in case of GSM Gateway)
		$callerid="";
		$wakka = new KHRMSLib();

		//TODO::Need To Add Sequence Logic Here
		$users=$wakka->getPersons("client='$client' and status='New' and mobile!='' limit 1");

		if(sizeof($users)>=1)
		{
			$record=$wakka->getPerson($users[0]['id']);
			if($record)
			{
				$record["peopledata"]["status"]="AutoCall";
				$wakka->setPerson($users[0]['id'],$record);
			}

			$dialline->user_id=$user_id;
			$dialline->status="AutoCall";
			$dialline->regexstr=$users[0]['client'];
			$dialline->number=$users[0]["mobile"];
			$dialline->save();

			$nowts=microtime(true)*1000;

		//start the call log
			$crmcall=new CRMCall();
			$crmcall->number=$users[0]["mobile"];
			$crmcall->user_id=0;
			$crmcall->sipid_id=0;
			$crmcall->crm_id=$users[0]['id'];
			$crmcall->client=$users[0]['client'];
			$crmcall->department=$users[0]['department'];
			$crmcall->state='New';
			$crmcall->type="AutoCall";
			$crmcall->dialline_id=$dialline->id;

			$crmcall->setTs('ts_Wait',$nowts);
			$crmcall->setTs('ts_Call',$nowts);

			$crmcall->did=$callerid;

			$tdata=array();
			$crmcall->data=json_encode($tdata);
			$crmcall->save();

		//start actual calls
			$newqueue=new Kqueue();
			$newqueue->autoCallOut($users[0]["mobile"],$callerid,$crmcall,$dialline);
		}

		return;
	}

	public function getSpanCount()
	{
		$spanArr = array("span1" => 30, "span2" => 0, "span3" => 0, "span4" => 0);

		$cnt = array_sum($spanArr);

		return $cnt;
	}
}