PageRenderTime 28ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/lms_debug/protected/controllers/CronController.php

https://gitlab.com/badelal143/lms_debug
PHP | 2546 lines | 2025 code | 385 blank | 136 comment | 325 complexity | e2db7cfa969ee7f00d2fd8d19ea249b1 MD5 | raw file
Possible License(s): LGPL-2.1, LGPL-3.0, LGPL-2.0
  1. <?php
  2. class CronController extends Controller
  3. {
  4. const SHARED_TITLE = "Admin Panel";
  5. /**
  6. * Declares class-based actions.
  7. */
  8. public function filters()
  9. {
  10. //return array( 'accessControl' ); // perform access control for CRUD operations
  11. }
  12. public function actions()
  13. {
  14. return array(
  15. // captcha action renders the CAPTCHA image displayed on the contact page
  16. 'captcha'=>array(
  17. 'class'=>'CCaptchaAction',
  18. 'backColor'=>0xFFFFFF,
  19. ),
  20. // page action renders "static" pages stored under 'protected/views/site/pages'
  21. // They can be accessed via: index.php?r=site/page&view=FileName
  22. 'page'=>array(
  23. 'class'=>'CViewAction',
  24. ),
  25. );
  26. }
  27. /**
  28. * It calls the actionCreateExcel to generates excel reports'
  29. * when an action is not explicitly requested by users.
  30. */
  31. public function actionExportExcelReport()
  32. {
  33. // It calls the actionCreateExcel to generates excel reports'
  34. @$getName=$_POST['LeadCronReport']['name'];
  35. @$getStatus=$_POST['LeadCronReport']['status'];
  36. @$getStage=$_POST['LeadCronReport']['stage'];
  37. @$date1=$_POST['LeadCronReport']['period1'];
  38. @$date2=$_POST['LeadCronReport']['period2'];
  39. @$getleadSourceId=$_POST['LeadCronReport']['leadSourceId'];
  40. @$getleadStatusId=$_POST['leadStatusId'];
  41. @$datetype=@$_POST['LeadCronReport']['datetype'];
  42. if(isset($datetype) && !empty($datetype)){
  43. $datetype=$datetype;
  44. } else {
  45. $datetype='updatedOn';
  46. }
  47. $isjunk = @$_REQUEST['isJunk'];
  48. $isjunk = $isjunk?$isjunk:'no';
  49. $this->actionCreateExcel($getName,$getStatus,$getStage,$date1,$date2,$getleadSourceId,$getleadStatusId,$datetype,$isjunk);
  50. }
  51. public function actionreports() {
  52. // renders the view file 'protected/views/site/index.php'
  53. // using the default layout 'protected/views/layouts/main.php'
  54. $model=new LeadCronReport('search');
  55. $model->scenario = 'LeadCronReport';
  56. $teamId = '';
  57. $teamUserId = '';
  58. if(@$_POST['LeadCronReport'] !='' && isset($_POST['LeadCronReport'])){
  59. @$primaryLeadStatus = @$_POST['leadStatusId'];
  60. if(count($primaryLeadStatus) > 0){
  61. $primaryLeadStatus = implode(",",$primaryLeadStatus);
  62. $primaryDisposition=Yii::app()->db->createCommand("select leadStatus.leadStatus,leadStatusId from leadStatus where parentId IN (".@$primaryLeadStatus.") ")->queryAll();
  63. if(count($primaryDisposition) > 0){
  64. for($w=0;$w<count($primaryDisposition);$w++){
  65. @$PrimaryDispositionIds[] = @$primaryDisposition[$w]['leadStatusId'];
  66. }
  67. } else {
  68. @$PrimaryDispositionIds[] = '';
  69. }
  70. @$PrimaryDispositionIds = implode(",",@$PrimaryDispositionIds);
  71. } else {
  72. @$PrimaryDispositionIds = '';
  73. }
  74. $teamId = @$_POST['Team']['teamId'];
  75. $teamUserId = @$_POST['Team']['teamMemberId'];
  76. if($teamUserId=='' or empty($teamUserId)){
  77. $teamUsers=Yii::app()->db->createCommand("select userId from teamUserMapping where teamId = '".@$teamId."' ")->queryAll();
  78. $reportsteamUsersIds = array();
  79. foreach($teamUsers as $key=>$value){
  80. $reportsteamUsersIds[] = $value['userId'];
  81. }
  82. } else {
  83. $reportsteamUsersIds[] = $teamUserId;
  84. }
  85. $name=@$_POST['LeadCronReport']['name'];
  86. $status=@$_POST['LeadCronReport']['status'];
  87. $stage=@$_POST['LeadCronReport']['stage'];
  88. /*$utmCode=@$_POST['LeadCronReport']['utmCode'];
  89. $teleCaller=@$_POST['LeadCronReport']['teleCaller'];*/
  90. $period1=@$_POST['LeadCronReport']['period1'];
  91. $period2=@$_POST['LeadCronReport']['period2'];
  92. $leadSourceId=@$_POST['LeadCronReport']['leadSourceId'];
  93. $ws_agentid=@$_POST['LeadCronReport']['ws_agentid'];
  94. $datetype=@$_POST['LeadCronReport']['datetype'];
  95. $isjunk = @$_REQUEST['isJunk'];
  96. $isjunk = $isjunk?$isjunk:'no';
  97. if(isset($datetype) && !empty($datetype)){
  98. $datetype=$datetype;
  99. } else {
  100. $datetype='updatedOn';
  101. }
  102. //echo $datetype; die;
  103. $criteria = new CDbCriteria;
  104. $criteria->select = 't.*,`city`.`city`,`state`.`state`, `leadSourceMaster`.`leadSourceTitle`, `leadStageMaster`.`leadStage`,`leadStatus`.`leadStatus`,`customerTypeMaster`.`customerType`,`productMaster`.`productName`,`policyTypeMaster`.`policyType`,`planTypeMaster`.`planType`,`campaign`.`campaignName`';
  105. $criteria->join ='LEFT JOIN city ON (city.cityId = t.cityId) LEFT JOIN state ON (state.stateId = t.stateId) LEFT JOIN leadSourceMaster ON (leadSourceMaster.leadSourceId = t.leadSourceId) LEFT JOIN leadStageMaster ON (leadStageMaster.leadStageId = t.leadStageId)LEFT JOIN leadStatus ON (leadStatus.leadStatusId = t.leadStatusId)LEFT JOIN customerTypeMaster ON (customerTypeMaster.customerTypeId = t.customerTypeId)LEFT JOIN productMaster ON (productMaster.productId = t.productId)LEFT JOIN policyTypeMaster ON (policyTypeMaster.policyTypeId = t.policyTypeId)LEFT JOIN planTypeMaster ON (planTypeMaster.planTypeId = t.planTypeId)LEFT JOIN campaign ON (campaign.campaignId = t.campaignId)';
  106. $criteria->order='leadId DESC';
  107. if(count($reportsteamUsersIds) > 0){
  108. $comd = implode(',',$reportsteamUsersIds);
  109. $criteria->addCondition("t.currentAllocatedId IN (".$comd.") ");
  110. }
  111. if(isset($name) && !empty($name))
  112. {/*LIKE '$this->time_up%'";*/
  113. $criteria->addCondition("t.name like '%".$name."'");
  114. }
  115. if(isset($status) && !empty($status))
  116. {
  117. $criteria->addCondition("t.leadStatusId =".$status);
  118. }
  119. if(isset($PrimaryDispositionIds) && !empty($PrimaryDispositionIds))
  120. {
  121. $criteria->addCondition("t.leadStatusId IN (".@$PrimaryDispositionIds.") ");
  122. }
  123. if(isset($stage) && !empty($stage))
  124. {
  125. $criteria->addCondition("t.leadStageId =".$stage);
  126. }
  127. if(isset($leadSourceId) && !empty($leadSourceId))
  128. {
  129. $criteria->addCondition("t.leadSourceId =".$leadSourceId);
  130. }
  131. if(isset($isjunk) && !empty($isjunk) && $isjunk=='yes' )
  132. {
  133. $criteria->addCondition("t.leadStatusId !=36");
  134. }
  135. if(isset($ws_agentid) && !empty($ws_agentid))
  136. {
  137. $criteria->addCondition("t.ws_agentid='".$ws_agentid."'");
  138. }
  139. if((isset($period1) && !empty($period1)) && (isset($period2) && !empty($period2)))
  140. {
  141. $period1=strtotime($period1);
  142. $period2=strtotime($period2)+86399;
  143. // echo date('d m y :: h: i: s: A',$period2); die;
  144. $criteria->addCondition('t.'.$datetype.' >= '.$period1.' AND t.'.$datetype.' <= '.$period2.'');
  145. // $criteria->addBetweenCondition('t.'.$datetype,$period1,$period2,'');
  146. }
  147. /*echo "<pre>";
  148. print_r($criteria);
  149. die();*/
  150. $model->set_name=@$_POST['LeadCronReport']['name'];
  151. $model->set_stage=@$_POST['LeadCronReport']['stage'];
  152. $model->set_status=@$_POST['LeadCronReport']['status'];
  153. $model->set_period1=@$_POST['LeadCronReport']['period1'];
  154. $model->set_period2=@$_POST['LeadCronReport']['period2'];
  155. $model->set_leadStatusId=@$_POST['leadStatusId'];
  156. $model->set_leadSourceId=@$_POST['LeadCronReport']['leadSourceId'];
  157. $model->set_ws_agentid=@$_POST['LeadCronReport']['ws_agentid'];
  158. $criteria->order='leadId DESC';
  159. $dataProvider=new CActiveDataProvider('LeadCronReport', array('criteria'=>$criteria,'pagination'=>array(
  160. 'pageSize'=>20,
  161. 'params' => array('period1' =>@$period1?date("d-m-Y",@$period1):'','period2' =>@$period2?date("d-m-Y",@$period2):''),
  162. ),));
  163. $this->render('reports',array('model'=>$model,'dataProvider'=>$dataProvider,'teamId'=>$teamId,'teamUserId'=>$teamUserId));
  164. }else{
  165. $criteria = new CDbCriteria;
  166. $criteria->select = 't.*';
  167. $criteria->order='leadId DESC';
  168. $dataProvider=new CActiveDataProvider('LeadCronReport', array('criteria'=>$criteria,));
  169. $this->render('reports',array('model'=>$model,'dataProvider'=>$dataProvider,'teamId'=>$teamId,'teamUserId'=>$teamUserId));
  170. }
  171. }
  172. /**
  173. * This function is used to get column name from number of column
  174. * calls from 'actionCreateExcel' function.
  175. */
  176. public function getNameFromNumber($num) {
  177. $numeric = $num % 26;
  178. $letter = chr(65 + $numeric);
  179. $num2 = intval($num / 26);
  180. if ($num2 > 0) {
  181. return getNameFromNumber($num2 - 1) . $letter;
  182. } else {
  183. return $letter;
  184. }
  185. }
  186. public function getPageType()
  187. {
  188. return "Reports";
  189. }
  190. /**
  191. * This function is used to create excel file
  192. * calls from 'actionreports' function.
  193. */
  194. public function actionCreateExcel($getName,$getStatus,$getStage,$date1,$date2,$getleadSourceId,$getleadStatusId,$datetype,$isjunk){
  195. $paginationExcelValue = @$_POST['fetchrecordsBydropdown'];
  196. if(isset($paginationExcelValue) && !empty($paginationExcelValue)){
  197. $explodedpaginationValue = explode('-',$paginationExcelValue);
  198. $startLimit = $explodedpaginationValue[0];
  199. $endLimit = 10000;
  200. } else {
  201. $startLimit = '';
  202. $endLimit = '';
  203. }
  204. if(isset($startLimit) && isset($endLimit) && !empty($endLimit)){
  205. $limitCond = " limit $startLimit , $endLimit";
  206. } else {
  207. $limitCond = '';
  208. }
  209. //Here is the code to set conditions for fetch records from database
  210. $condfilter = '';
  211. if((isset($getName)&& (!empty($getName))) || (isset($getStatus)&& (!empty($getStatus))) || (isset($getStage)&& (!empty($getStage)))|| (isset($date1)&& (!empty($date1))) || (isset($date2)&& (!empty($date2))))
  212. {
  213. if(isset($getName) && !empty($getName))
  214. {
  215. $condfilter .= "t.name like '%".$getName."' AND ";
  216. }
  217. if(isset($getStatus) && !empty($getStatus))
  218. {
  219. $condfilter .= "t.leadStatusId =".$getStatus." AND ";
  220. }
  221. if(isset($getStage) && !empty($getStage))
  222. {
  223. $condfilter .= "t.leadStageId =".$getStage." AND ";
  224. }
  225. if(isset($getleadSourceId) && !empty($getleadSourceId))
  226. {
  227. $condfilter .= "t.leadSourceId =".$getleadSourceId." AND ";
  228. }
  229. if(isset($isjunk) && !empty($isjunk))
  230. {
  231. $condfilter .= "t.leadStatusId != 36 AND ";
  232. }
  233. if((isset($date1) && !empty($date1)) && (isset($date2) && !empty($date2)))
  234. {
  235. $date1=strtotime($date1);
  236. $date2=strtotime($date2)+86399;
  237. $condfilter .= "t.".$datetype." >=".$date1." AND t.".$datetype." <= ".$date2." AND ";
  238. }
  239. if(isset($condfilter) && !empty($condfilter)){
  240. $wherecon = "WHERE ";
  241. } else {
  242. $wherecon = "";
  243. }
  244. $data=Yii::app()->db->createCommand("select t.leadId,t.name,t.mobile,t.email,t.members,t.premium,t.productDetails,t.ws_agentid,t.status,t.isJunk,t.leadDescription,t.currentAllocatedId,t.createdBy,t.updatedOn,t.jsonAllData from leads_cron as t $wherecon $condfilter t.leadId > 0 order by t.leadId DESC $limitCond")->queryAll();
  245. }else{
  246. if(isset($getleadSourceId) && !empty($getleadSourceId))
  247. {
  248. $condfilter .= "t.leadSourceId =".$getleadSourceId." AND";
  249. }
  250. if(count($getleadStatusId) > 0){
  251. $getleadStatusId = implode(",",$getleadStatusId);
  252. $primaryDisposition=Yii::app()->db->createCommand("select leadStatus.leadStatus,leadStatusId from leadStatus where parentId IN (".@$getleadStatusId.") ")->queryAll();
  253. if(count($primaryDisposition) > 0){
  254. for($w=0;$w<count($primaryDisposition);$w++){
  255. @$PrimaryDispositionIds[] = @$primaryDisposition[$w]['leadStatusId'];
  256. }
  257. } else {
  258. @$PrimaryDispositionIds[] = '';
  259. }
  260. @$PrimaryDispositionIds = implode(",",@$PrimaryDispositionIds);
  261. } else {
  262. @$PrimaryDispositionIds = '';
  263. }
  264. if(isset($PrimaryDispositionIds) && !empty($PrimaryDispositionIds))
  265. {
  266. $condfilter .= "t.leadStatusId IN (".@$PrimaryDispositionIds.") AND ";
  267. }
  268. if(isset($condfilter) && !empty($condfilter)){
  269. $wherecon = "WHERE ";
  270. } else {
  271. $wherecon = "";
  272. }
  273. $data=Yii::app()->db->createCommand("select t.leadId,t.name,t.mobile,t.email,t.members,t.premium,t.productDetails,t.ws_agentid,t.status,t.isJunk,t.leadDescription,t.currentAllocatedId,t.createdBy,t.updatedOn,t.jsonAllData from leads_cron as t $wherecon $condfilter t.leadId > 0 order by t.leadId DESC $limitCond ")->queryAll();
  274. }
  275. if(count($data)>0){
  276. $file_name = "lms" . "_" . date("Y-m-d_H-i", time()) . ".csv";
  277. header('Content-Type: text/html; charset=utf-8');
  278. header("Content-type: application/octet-stream");
  279. header("Content-Disposition: attachment; filename=\"$file_name\"");
  280. header("Cache-Control: cache, must-revalidate");
  281. header("Pragma: public");
  282. $col = array(
  283. 'SNO.','Name','Mobile Number',' Email Id','Address','City','State','Members','Premium','Product Details','Lead Status','Status','isJunk','Lead Source','Lead Stage','Lead Description','Activity Description','Customer Type','Product Name','Policy Type','Plan Type','Campaign Name','UTM Code','Owner','Last Modified Date','Agent-Id');
  284. foreach ($col as $key => $value) {
  285. echo $value . ",";
  286. }
  287. echo "\n";
  288. $i=1;
  289. foreach ($data as $key => $value) {
  290. $jsonArray = json_decode($value['jsonAllData']);
  291. $state = $jsonArray->state;
  292. $city = $jsonArray->city;
  293. $product = $jsonArray->product;
  294. $leadStatus = $jsonArray->leadStatus;
  295. $leadSource = $jsonArray->leadSource;
  296. $leadStage = $jsonArray->leadStage;
  297. $ActivityDescription = $jsonArray->ActivityDescription;
  298. $owner = $jsonArray->owner;
  299. $customerType = $jsonArray->customerType;
  300. $policyType = $jsonArray->policyType;
  301. $planType = $jsonArray->planType;
  302. $campaign = $jsonArray->campaign;
  303. // $sqlDesc = "select group_concat(description) as ActivityDescription from leadFollowup where leadId=".@$value["leadId"]." ";
  304. // $dataDesc=Yii::app()->db->createCommand($sqlDesc)->queryAll();
  305. // $leadActivity = @$dataDesc[0]['ActivityDescription']?str_replace(",","/",@$dataDesc[0]['ActivityDescription']):'';
  306. if($value['currentAllocatedId']==$value['createdBy']){
  307. $owner = $owner."(C)";
  308. } else {
  309. $owner = $owner;
  310. }
  311. $lastModifieddate = date("d-M-Y H-i-s A",$value['updatedOn']);
  312. echo $i++ . ",";
  313. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["name"])) . ",";
  314. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value["mobile"])) . ",";
  315. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$value["email"])) . ",";
  316. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$value["address"])) . ",";
  317. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$city)) . ",";
  318. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$state)) . ",";
  319. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value["members"])) . ",";
  320. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value["premium"])) . ",";
  321. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value['productDetails'])) . ",";
  322. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$leadStatus)) . ",";
  323. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value["status"])) . ",";
  324. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value["isJunk"])) . ",";
  325. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$leadSource)) . ",";
  326. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$leadStage)) . ",";
  327. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$value["leadDescription"])) . ",";
  328. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$ActivityDescription)) . ",";
  329. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$customerType)) . ",";
  330. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$product)) . ",";
  331. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$policyType)) . ",";
  332. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$planType)) . ",";
  333. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$campaign)) . ",";
  334. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value["leadSourceCode"])) . ",";
  335. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$owner)) . ",";
  336. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$lastModifieddate)) . ",";
  337. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value["ws_agentid"])) . ",";
  338. echo "\n";
  339. }
  340. }
  341. else{
  342. $this->redirect('index.php?r=reports/reports');
  343. //$dataProvider=new CActiveDataProvider('LeadCronReport', array('criteria'=>@$criteria,));
  344. //$this->render('reports',array('model'=>$model,'dataProvider'=>$dataProvider));
  345. }
  346. }
  347. public function getLeadDescription($leadId){
  348. $records=Yii::app()->db->createCommand("select leadDescription from lead where leadId='".@$leadId."' ")->queryAll();
  349. if(count($records) > 0) {
  350. for($i=0;$i<count($records);$i++){
  351. $record[] = @$records[$i]['leadDescription'];
  352. }
  353. } else {
  354. echo "";
  355. }
  356. if( count(@$record) > 1){
  357. echo "<label title='".implode(',',$record)."'><a href='#'>".substr(implode(',',$record),0,5)."...</a></label>";
  358. } else if( count(@$record) == 1) {
  359. echo "<label title='".implode(',',@$record)."'><a href='#'>".implode(',',$record)."</a></label>";
  360. } else {
  361. echo "";
  362. }
  363. //echo explode(',',$agentId);
  364. }
  365. public function getLeadActivityDescription($leadId){
  366. $records=Yii::app()->db->createCommand("select description from leadFollowup where leadId='".@$leadId."' ")->queryAll();
  367. if(count($records) > 0) {
  368. for($i=0;$i<count($records);$i++){
  369. $record[] = @$records[$i]['description'];
  370. }
  371. } else {
  372. echo "";
  373. }
  374. if( count(@$record) > 1){
  375. echo "<label title='".implode(',',$record)."'><a href='#'>".substr(implode(',',$record),0,5)."...</a></label>";
  376. } else if( count(@$record) == 1) {
  377. echo "<label title='".implode(',',@$record)."'><a href='#'>".substr(implode(',',$record),0,5)."...</a></label>";
  378. } else {
  379. echo "";
  380. }
  381. //echo explode(',',$agentId);
  382. }
  383. public function getLeadActivityDescriptionExcel($leadId){
  384. $records=Yii::app()->db->createCommand("select description from leadFollowup where leadId='".@$leadId."' ")->queryAll();
  385. if(count($records) > 0) {
  386. for($i=0;$i<count($records);$i++){
  387. $record[] = @$records[$i]['description'];
  388. }
  389. } else {
  390. echo "";
  391. }
  392. if( count(@$record) > 1){
  393. echo implode(',',$record);
  394. } else if( count(@$record) == 1) {
  395. echo implode(',',$record);
  396. } else {
  397. echo "";
  398. }
  399. //echo explode(',',$agentId);
  400. }
  401. public function actionCheckanddelete(){
  402. $reportmodel=Lead::model()->findAll();
  403. print_r($reportmodel);
  404. die;
  405. }
  406. function actioncroneJobForReport(){
  407. ini_set('max_input_time', 1200);
  408. ini_set('max_execution_time', 1200);
  409. $sourcewiseDetails=Yii::app()->db->createCommand("select * from leads_cron_history where id='lead_updated_on' ")->queryAll();
  410. $sourcewiseDetails[0]['updatedOn'];
  411. $queryUpdatedOn = "select t.*,`user`.`id`,`user`.`firstName`,`user`.`lastName`,`city`.`city`, `state`.`state`, `leadSourceMaster`.`leadSourceTitle`,`leadSourceMaster`.`leadSourceCode`,`leadStageMaster`.`leadStage`,`leadStatus`.`leadStatus`, `customerTypeMaster`.`customerType`,`productMaster`.`productName`,`policyTypeMaster`.`policyType`,`planTypeMaster`.`planType`,`campaign`.`campaignName` from lead as t LEFT JOIN city ON (city.cityId = t.cityId) LEFT JOIN state ON (state.stateId = t.stateId) LEFT JOIN leadSourceMaster ON (leadSourceMaster.leadSourceId = t.leadSourceId) LEFT JOIN leadStageMaster ON (leadStageMaster.leadStageId = t.leadStageId)LEFT JOIN leadStatus ON (leadStatus.leadStatusId = t.leadStatusId)LEFT JOIN customerTypeMaster ON (customerTypeMaster.customerTypeId = t.customerTypeId)LEFT JOIN productMaster ON (productMaster.productId = t.productId) LEFT JOIN policyTypeMaster ON (policyTypeMaster.policyTypeId = t.policyTypeId)LEFT JOIN planTypeMaster ON (planTypeMaster.planTypeId = t.planTypeId) LEFT JOIN campaign ON (campaign.campaignId = t.campaignId) LEFT JOIN user ON (user.id=t.currentAllocatedId) where (t.updatedOn > ".@$sourcewiseDetails[0]['updatedOn']." || t.createdOn > ".@$sourcewiseDetails[0]['updatedOn']." ) order by t.leadId DESC ";
  412. $dataUpdatedOn=Yii::app()->db->createCommand($queryUpdatedOn)->queryAll();
  413. $updateleads_cron_history = " update leads_cron_history set updated_ts = '".date('Y-m-d H:i:s')."',updatedOn = '".time()."' where id='lead_updated_on' ";
  414. $executeQueryder=Yii::app()->db->createCommand($updateleads_cron_history)->execute();
  415. //$queryCreatedOn = "select t.leadId,t.name,t.mobile,t.email,t.members,t.premium,t.productDetails,t.ws_agentid,t.status,t.isJunk,t.leadDescription,t.currentAllocatedId,t.createdBy,t.updatedOn,`user`.`id`,`user`.`firstName`,`user`.`lastName`,`city`.`city`, `state`.`state`, `leadSourceMaster`.`leadSourceTitle`,`leadSourceMaster`.`leadSourceCode`,`leadStageMaster`.`leadStage`,`leadStatus`.`leadStatus`, `customerTypeMaster`.`customerType`,`productMaster`.`productName`,`policyTypeMaster`.`policyType`,`planTypeMaster`.`planType`,`campaign`.`campaignName` from lead as t LEFT JOIN city ON (city.cityId = t.cityId) LEFT JOIN state ON (state.stateId = t.stateId) LEFT JOIN leadSourceMaster ON (leadSourceMaster.leadSourceId = t.leadSourceId) LEFT JOIN leadStageMaster ON (leadStageMaster.leadStageId = t.leadStageId)LEFT JOIN leadStatus ON (leadStatus.leadStatusId = t.leadStatusId)LEFT JOIN customerTypeMaster ON (customerTypeMaster.customerTypeId = t.customerTypeId)LEFT JOIN productMaster ON (productMaster.productId = t.productId) LEFT JOIN policyTypeMaster ON (policyTypeMaster.policyTypeId = t.policyTypeId)LEFT JOIN planTypeMaster ON (planTypeMaster.planTypeId = t.planTypeId) LEFT JOIN campaign ON (campaign.campaignId = t.campaignId) LEFT JOIN user ON (user.id=t.currentAllocatedId) where t.leadId <= 2 and createdOn > ".@$sourcewiseDetails[0]['updatedOn']." order by t.leadId DESC ";
  416. //$dataCreatedOn=Yii::app()->db->createCommand($queryCreatedOn)->queryAll();
  417. $insertcount=0;
  418. $updatecount=0;
  419. if(count($dataUpdatedOn) > 0){
  420. foreach ($dataUpdatedOn as $key => $value) {
  421. $owner = @$value['firstName']?(@$value['firstName']." ".@$value['lastName']):"NA";
  422. $sqlDesc = "select group_concat(description) as ActivityDescription from renewalleadFollowup where leadId=".@$value["leadId"]." ";
  423. $dataDesc=Yii::app()->db->createCommand($sqlDesc)->queryAll();
  424. $leadActivity = @$dataDesc[0]['ActivityDescription']?str_replace(",",":",@$dataDesc[0]['ActivityDescription']):'';
  425. $state = @$value["state"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["state"])):'NA';
  426. $city = @$value["city"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["city"])):'NA';
  427. $customerType = @$value["customerType"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["customerType"])):'NA';
  428. $productName = @$value["productName"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["productName"])):'NA';
  429. $policyType = @$value["policyType"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["policyType"])):'NA';
  430. $planType = @$value["planType"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["planType"])):'NA';
  431. $campaignName = @$value["campaignName"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["campaignName"])):'NA';
  432. $leadSourceTitle = @$value["leadSourceTitle"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["leadSourceTitle"])):'NA';
  433. $leadStatus = @$value["leadStatus"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["leadStatus"])):'NA';
  434. $leadStage = @$value["leadStage"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["leadStage"])):'NA';
  435. $owner = @$owner?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$owner)):'NA';
  436. $agntName = @$value["agntName"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["agntName"])):'NA';
  437. $leadActivity = @$leadActivity?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$leadActivity)):'NA';
  438. $newarray = array(
  439. 'state' => $state,
  440. 'city' => $city,
  441. 'customerType' => $customerType,
  442. 'product' => $productName,
  443. 'policyType' => $policyType,
  444. 'planType' => $planType,
  445. 'campaign' => $campaignName,
  446. 'leadSource' => $leadSourceTitle,
  447. 'leadStatus' => $leadStatus,
  448. 'leadStage' => $leadStage,
  449. 'owner' => addslashes($owner),
  450. 'agntName' => $agntName,
  451. 'ActivityDescription' => str_replace("'","`",$leadActivity)
  452. );
  453. $jsonData = json_encode($newarray);
  454. //$insertQuery = " insert into leads_cron (leadId,name,email,emailOptOut,mobile,mobileOptOut,address,stateId,cityId,customerTypeId,productId,policyTypeId,planTypeId,campaignId,members,si,premium,productDetails,ageGroup,children,leadSourceId,leadStatusId,leadStageId,isJunk,currentAllocatedId,currentAllocatedDate,isDuplicate,duplicateLeadId,age,dateonSubmit,fileName,leadDescription,isRead,status,ipaddress,agentId,createdOn,createdBy,updatedOn,updatedBy,ws_sourcecode,ws_subject,ws_telephone,ws_plan,ws_product,ws_quoteid,ws_proposalid,ws_leadstage,ws_agentid,ws_noofyears,ws_orgnaizationName,utmsource,isBulkImport,salesClosedUpdatedOn,jsonAllData,jsonDataUpdatedOn,jsonDataUpdatedBy) values (".$value['leadId'].",".$value['name'].",".$value['email'].",".$value['emailOptOut'].",".$value['mobile'].",".$value['mobileOptOut'].",".$value['address'].",".$value['stateId'].",".$value['cityId'].",".$value['customerTypeId'].",".$value['productId'].",".$value['policyTypeId'].",".$value['planTypeId'].",".$value['campaignId'].",".$value['members'].",".$value['si'].",".$value['premium'].",".$value['productDetails'].",".$value['ageGroup'].",".$value['children'].",".$value['leadSourceId'].",".$value['leadStatusId'].",".$value['leadStageId'].",".$value['isJunk'].",".$value['currentAllocatedId'].",".$value['currentAllocatedDate'].",".$value['isDuplicate'].",".$value['duplicateLeadId'].",".$value['age'].",".$value['dateonSubmit'].",".$value['fileName'].",".$value['leadDescription'].",".$value['isRead'].",".$value['status'].",".$value['ipaddress'].",".$value['agentId'].",".$value['createdOn'].",".$value['createdBy'].",".$value['updatedOn'].",".$value['updatedBy'].",".$value['ws_sourcecode'].",".$value['ws_subject'].",".$value['ws_telephone'].",".$value['ws_plan'].",".$value['ws_product'].",".$value['ws_quoteid'].",".$value['ws_proposalid'].",".$value['ws_leadstage'].",".$value['ws_agentid'].",".$value['ws_noofyears'].",".$value['ws_orgnaizationName'].",".$value['utmsource'].",".$value['isBulkImport'].",".$value['salesClosedUpdatedOn'].",'".$jsonData."',".$value['jsonDataUpdatedOn'].",".$value['jsonDataUpdatedBy'].") ";
  455. if($value['createdOn'] >= $sourcewiseDetails[0]['updatedOn']){
  456. $insertQuery = " insert into leads_cron (leadId,name,email,emailOptOut,mobile,mobileOptOut,address,stateId,cityId,customerTypeId,productId,policyTypeId,planTypeId,campaignId,members,si,premium,productDetails,ageGroup,children,leadSourceId,leadStatusId,leadStageId,isJunk,currentAllocatedId,currentAllocatedDate,isDuplicate,duplicateLeadId,age,dateonSubmit,fileName,leadDescription,isRead,status,ipaddress,agentId,createdOn,createdBy,updatedOn,updatedBy,ws_sourcecode,ws_subject,ws_telephone,ws_plan,ws_product,ws_quoteid,ws_proposalid,ws_leadstage,ws_agentid,ws_noofyears,ws_orgnaizationName,utmsource,isBulkImport,salesClosedUpdatedOn,jsonAllData,jsonDataUpdatedOn,jsonDataUpdatedBy) values ('".$value['leadId']."','".addslashes($value['name'])."','".$value['email']."','".$value['emailOptOut']."','".$value['mobile']."','".$value['mobileOptOut']."','".addslashes($value['address'])."','".$value['stateId']."','".$value['cityId']."','".$value['customerTypeId']."','".$value['productId']."','".$value['policyTypeId']."','".$value['planTypeId']."','".$value['campaignId']."','".addslashes($value['members'])."','".addslashes($value['si'])."','".addslashes($value['premium'])."','".addslashes($value['productDetails'])."','".$value['ageGroup']."','".$value['children']."','".$value['leadSourceId']."','".$value['leadStatusId']."','".$value['leadStageId']."','".$value['isJunk']."','".$value['currentAllocatedId']."','".$value['currentAllocatedDate']."','".$value['isDuplicate']."','".$value['duplicateLeadId']."','".$value['age']."','".$value['dateonSubmit']."','".$value['fileName']."','".addslashes($value['leadDescription'])."','".$value['isRead']."','".$value['status']."','".$value['ipaddress']."','".$value['agentId']."','".$value['createdOn']."','".$value['createdBy']."','".$value['updatedOn']."','".$value['updatedBy']."','".$value['ws_sourcecode']."','".$value['ws_subject']."','".$value['ws_telephone']."','".$value['ws_plan']."','".$value['ws_product']."','".$value['ws_quoteid']."','".$value['ws_proposalid']."','".$value['ws_leadstage']."','".$value['ws_agentid']."','".$value['ws_noofyears']."','".$value['ws_orgnaizationName']."','".$value['utmsource']."','".$value['isBulkImport']."','".$value['salesClosedUpdatedOn']."','".$jsonData."','".time()."','amit') ";
  457. $executeQuery4=Yii::app()->db->createCommand($insertQuery)->execute();
  458. //echo "<br><br>" .$insertQuery;
  459. $insertcount++;
  460. } else if($value['updatedOn'] >= $sourcewiseDetails[0]['updatedOn']){
  461. $updateQuery = " update leads_cron set leadId='".$value['leadId']."',name='".addslashes($value['name'])."',email='".$value['email']."',emailOptOut='".$value['emailOptOut']."',mobile='".$value['mobile']."',mobileOptOut='".$value['mobileOptOut']."',address='".addslashes($value['address'])."',stateId='".$value['stateId']."',cityId='".$value['cityId']."',customerTypeId='".$value['customerTypeId']."',productId='".$value['productId']."',policyTypeId='".$value['policyTypeId']."',planTypeId='".$value['planTypeId']."',campaignId='".$value['campaignId']."',members='".addslashes($value['members'])."',si='".addslashes($value['si'])."',premium='".addslashes($value['premium'])."',productDetails='".addslashes($value['productDetails'])."',ageGroup='".$value['ageGroup']."',children='".$value['children']."',leadSourceId='".$value['leadSourceId']."',leadStatusId='".$value['leadStatusId']."',leadStageId='".$value['leadStageId']."',isJunk='".$value['isJunk']."',currentAllocatedId='".$value['currentAllocatedId']."',currentAllocatedDate='".$value['currentAllocatedDate']."',isDuplicate='".$value['isDuplicate']."',duplicateLeadId='".$value['duplicateLeadId']."',age='".$value['age']."',dateonSubmit='".$value['dateonSubmit']."',fileName='".$value['fileName']."',leadDescription='".addslashes($value['leadDescription'])."',isRead='".$value['isRead']."',status='".$value['status']."',ipaddress='".$value['ipaddress']."',agentId='".$value['agentId']."',createdOn='".$value['createdOn']."',createdBy='".$value['createdBy']."',updatedOn='".$value['updatedOn']."',updatedBy='".$value['updatedBy']."',ws_sourcecode='".$value['ws_sourcecode']."',ws_subject='".$value['ws_subject']."',ws_telephone='".$value['ws_telephone']."',ws_plan='".$value['ws_plan']."',ws_product='".$value['ws_product']."',ws_quoteid='".$value['ws_quoteid']."',ws_proposalid='".$value['ws_proposalid']."',ws_leadstage='".$value['ws_leadstage']."',ws_agentid='".$value['ws_agentid']."',ws_noofyears='".$value['ws_noofyears']."',ws_orgnaizationName='".$value['ws_orgnaizationName']."',utmsource='".$value['utmsource']."',isBulkImport='".$value['isBulkImport']."',salesClosedUpdatedOn='".$value['salesClosedUpdatedOn']."',jsonAllData='".$jsonData."',jsonDataUpdatedOn='".time()."',jsonDataUpdatedBy='amit' where leadId = ".@$value['leadId']." ";
  462. $executeQuery2=Yii::app()->db->createCommand($updateQuery)->execute();
  463. //echo "<br><br>" .$updateQuery;
  464. $updatecount++;
  465. }
  466. }
  467. }
  468. echo "insert count=".$insertcount." and update count=".$updatecount;
  469. }
  470. function actioncroneFirstTime(){
  471. $startId = @$_REQUEST['startId'];
  472. $endId = @$_REQUEST['endId'];
  473. if(empty($startId) || empty($endId)){
  474. echo "parameter missing";
  475. die;
  476. }
  477. if($startId > $endId){
  478. echo "start Limit can not be greater or equal to end Limit";
  479. die;
  480. }
  481. $query = "select t.*,`user`.`id`,`user`.`firstName`,`user`.`lastName`,`city`.`city`, `state`.`state`, `leadSourceMaster`.`leadSourceTitle`,`leadSourceMaster`.`leadSourceCode`,`leadStageMaster`.`leadStage`,`leadStatus`.`leadStatus`, `customerTypeMaster`.`customerType`,`productMaster`.`productName`,`policyTypeMaster`.`policyType`,`planTypeMaster`.`planType`,`campaign`.`campaignName` from lead as t LEFT JOIN city ON (city.cityId = t.cityId) LEFT JOIN state ON (state.stateId = t.stateId) LEFT JOIN leadSourceMaster ON (leadSourceMaster.leadSourceId = t.leadSourceId) LEFT JOIN leadStageMaster ON (leadStageMaster.leadStageId = t.leadStageId)LEFT JOIN leadStatus ON (leadStatus.leadStatusId = t.leadStatusId)LEFT JOIN customerTypeMaster ON (customerTypeMaster.customerTypeId = t.customerTypeId)LEFT JOIN productMaster ON (productMaster.productId = t.productId) LEFT JOIN policyTypeMaster ON (policyTypeMaster.policyTypeId = t.policyTypeId)LEFT JOIN planTypeMaster ON (planTypeMaster.planTypeId = t.planTypeId) LEFT JOIN campaign ON (campaign.campaignId = t.campaignId) LEFT JOIN user ON (user.id=t.currentAllocatedId) where t.leadId >= $startId and t.leadId <= $endId ";
  482. $data=Yii::app()->db->createCommand($query)->queryAll();
  483. $updateleads_cron_history = " update leads_cron_history set updated_ts = '".date('Y-m-d H:i:s')."',updatedOn = '".time()."' where id='lead_updated_on' ";
  484. $executeQuery=Yii::app()->db->createCommand($updateleads_cron_history)->execute();
  485. //$r=0;
  486. foreach ($data as $key => $value) {
  487. $owner = @$value['firstName']?(@$value['firstName']." ".@$value['lastName']):"NA";
  488. $sqlDesc = "select group_concat(description) as ActivityDescription from renewalleadFollowup where leadId=".@$value["leadId"]." ";
  489. $dataDesc=Yii::app()->db->createCommand($sqlDesc)->queryAll();
  490. $leadActivity = @$dataDesc[0]['ActivityDescription']?str_replace(",",":",@$dataDesc[0]['ActivityDescription']):'';
  491. $state = @$value["state"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["state"])):'NA';
  492. $city = @$value["city"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["city"])):'NA';
  493. $customerType = @$value["customerType"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["customerType"])):'NA';
  494. $productName = @$value["productName"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["productName"])):'NA';
  495. $policyType = @$value["policyType"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["policyType"])):'NA';
  496. $planType = @$value["planType"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["planType"])):'NA';
  497. $campaignName = @$value["campaignName"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["campaignName"])):'NA';
  498. $leadSourceTitle = @$value["leadSourceTitle"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["leadSourceTitle"])):'NA';
  499. $leadStatus = @$value["leadStatus"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["leadStatus"])):'NA';
  500. $leadStage = @$value["leadStage"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["leadStage"])):'NA';
  501. $owner = @$owner?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$owner)):'NA';
  502. $agntName = @$value["agntName"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["agntName"])):'NA';
  503. $leadActivity = @$leadActivity?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$leadActivity)):'NA';
  504. $newarray = array(
  505. 'state' => $state,
  506. 'city' => $city,
  507. 'customerType' => addslashes($customerType),
  508. 'product' => addslashes($productName),
  509. 'policyType' => addslashes($policyType),
  510. 'planType' => addslashes($planType),
  511. 'campaign' => addslashes($campaignName),
  512. 'leadSource' => addslashes($leadSourceTitle),
  513. 'leadStatus' => addslashes($leadStatus),
  514. 'leadStage' => addslashes($leadStage),
  515. 'owner' => addslashes($owner),
  516. 'agntName' => addslashes($agntName),
  517. 'ActivityDescription' => str_replace("'","`",$leadActivity)
  518. );
  519. $jsonData = json_encode($newarray);
  520. $insertQuery = " insert into leads_cron (leadId,name,email,emailOptOut,mobile,mobileOptOut,address,stateId,cityId,customerTypeId,productId,policyTypeId,planTypeId,campaignId,members,si,premium,productDetails,ageGroup,children,leadSourceId,leadStatusId,leadStageId,isJunk,currentAllocatedId,currentAllocatedDate,isDuplicate,duplicateLeadId,age,dateonSubmit,fileName,leadDescription,isRead,status,ipaddress,agentId,createdOn,createdBy,updatedOn,updatedBy,ws_sourcecode,ws_subject,ws_telephone,ws_plan,ws_product,ws_quoteid,ws_proposalid,ws_leadstage,ws_agentid,ws_noofyears,ws_orgnaizationName,utmsource,isBulkImport,salesClosedUpdatedOn,jsonAllData,jsonDataUpdatedOn,jsonDataUpdatedBy) values ('".$value['leadId']."','".addslashes($value['name'])."','".$value['email']."','".$value['emailOptOut']."','".$value['mobile']."','".$value['mobileOptOut']."','".addslashes($value['address'])."','".$value['stateId']."','".$value['cityId']."','".$value['customerTypeId']."','".$value['productId']."','".$value['policyTypeId']."','".$value['planTypeId']."','".$value['campaignId']."','".addslashes($value['members'])."','".addslashes($value['si'])."','".addslashes($value['premium'])."','".addslashes($value['productDetails'])."','".$value['ageGroup']."','".$value['children']."','".$value['leadSourceId']."','".$value['leadStatusId']."','".$value['leadStageId']."','".$value['isJunk']."','".$value['currentAllocatedId']."','".$value['currentAllocatedDate']."','".$value['isDuplicate']."','".$value['duplicateLeadId']."','".$value['age']."','".$value['dateonSubmit']."','".$value['fileName']."','".addslashes($value['leadDescription'])."','".$value['isRead']."','".$value['status']."','".$value['ipaddress']."','".$value['agentId']."','".$value['createdOn']."','".$value['createdBy']."','".$value['updatedOn']."','".$value['updatedBy']."','".$value['ws_sourcecode']."','".$value['ws_subject']."','".$value['ws_telephone']."','".$value['ws_plan']."','".$value['ws_product']."','".$value['ws_quoteid']."','".$value['ws_proposalid']."','".$value['ws_leadstage']."','".$value['ws_agentid']."','".$value['ws_noofyears']."','".$value['ws_orgnaizationName']."','".$value['utmsource']."','".$value['isBulkImport']."','".$value['salesClosedUpdatedOn']."','".$jsonData."','".time()."','amit') ";
  521. $executeQuerys=Yii::app()->db->createCommand($insertQuery)->execute();
  522. //echo $value['leadId']."<br>";
  523. // $r++;
  524. }
  525. }
  526. public function actionagentwisetotalcalls(){
  527. ini_set('max_input_time', 1200);
  528. ini_set('max_execution_time', 1200);
  529. $time = time();
  530. $parser = new CHtmlPurifier();
  531. $afterMonth = $parser->purify(intval(@$_REQUEST['month']));
  532. $afterDate = $parser->purify(intval(@$_REQUEST['date']));
  533. $afterYear = $parser->purify(intval(@$_REQUEST['year']));
  534. if(isset($afterMonth) && !empty($afterMonth) && isset($afterDate) && !empty($afterDate) && isset($afterYear) && !empty($afterYear)){
  535. $start = mktime(0, 0, 0,$afterMonth,$afterDate,$afterYear);
  536. $end = mktime(23, 59, 59,$afterMonth,$afterDate,$afterYear);
  537. } else {
  538. $start = mktime(0, 0, 0);
  539. $end = mktime(23, 59, 59);
  540. }
  541. $date = date('d_M_Y',$start)."_";
  542. $host = '10.216.6.59'; // MYSQL database host adress
  543. $db = 'lms'; // MYSQL database name
  544. $user = 'root'; // Mysql Datbase user
  545. $pass = '0kwp6aNR'; // Mysql Datbase password
  546. $link=mysql_connect($host,$user,$pass);
  547. mysql_select_db($db,$link);
  548. $table='report_agentwisetotalcalls';
  549. $filename = "filesystem/".$date.$table.'.csv';
  550. $csv_terminated = "\n";
  551. $csv_separator = ",";
  552. $csv_enclosed = '"';
  553. $csv_escaped = "\\";
  554. mysql_query("insert into report_info (id,type,filename,createdOn,createdBy,updatedOn,updatedBy) values('','agentwisetotalcalls','".@$filename."','".@$time."','0','".@$time."','0')");
  555. $totalleadstatusids = array(7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,33,26,37,38,39,42,43);
  556. $chktableExist = mysql_query('DROP TABLE IF EXISTS '.$table.' ') or die(mysql_error());
  557. $tableres ='create table IF NOT EXISTS '.$table.' as SELECT
  558. user.userName as `Caller Name`,
  559. SUM(CASE WHEN lead.currentAllocatedId=user.id THEN 1 ELSE 0 END) AS `Total Diposed`,
  560. SUM(CASE WHEN LS.`leadStatusId` = 7 THEN 1 ELSE 0 END) AS `Sale Done`,
  561. SUM(CASE WHEN LS.`leadStatusId` = 8 THEN 1 ELSE 0 END) AS `Follow Up`,
  562. SUM(CASE WHEN LS.`leadStatusId` = 9 THEN 1 ELSE 0 END) AS `Do Not Call - Will Buy self on Website`,
  563. SUM(CASE WHEN LS.`leadStatusId` = 10 THEN 1 ELSE 0 END) AS `Duplicate - Already In Talk With Team`,
  564. SUM(CASE WHEN LS.`leadStatusId` = 37 THEN 1 ELSE 0 END) AS `In Contact with Oflline Agent`,
  565. SUM(CASE WHEN LS.`leadStatusId` = 38 THEN 1 ELSE 0 END) AS `In Touch With Other Partner`,
  566. SUM(CASE WHEN LS.`leadStatusId` = 11 THEN 1 ELSE 0 END) AS `Short Hangup`,
  567. SUM(CASE WHEN LS.`leadStatusId` = 12 THEN 1 ELSE 0 END) AS `Call Later`,
  568. SUM(CASE WHEN LS.`leadStatusId` = 42 THEN 1 ELSE 0 END) AS `Ringing Less Than Five Tries`,
  569. SUM(CASE WHEN LS.`leadStatusId` = 43 THEN 1 ELSE 0 END) AS `Switched Off Less than Five Tries`,
  570. SUM(CASE WHEN LS.`leadStatusId` = 13 THEN 1 ELSE 0 END) AS `Not Interested - Fund Problem`,
  571. SUM(CASE WHEN LS.`leadStatusId` = 14 THEN 1 ELSE 0 END) AS `Just Checking Website`,
  572. SUM(CASE WHEN LS.`leadStatusId` = 15 THEN 1 ELSE 0 END) AS `Not Interested - Insured From Employer`,
  573. SUM(CASE WHEN LS.`leadStatusId` = 16 THEN 1 ELSE 0 END) AS `Not Interested - High Premium`,
  574. SUM(CASE WHEN LS.`leadStatusId` = 17 THEN 1 ELSE 0 END) AS `Under Age`,
  575. SUM(CASE WHEN LS.`leadStatusId` = 18 THEN 1 ELSE 0 END) AS `Not Visited Website`,
  576. SUM(CASE WHEN LS.`leadStatusId` = 19 THEN 1 ELSE 0 END) AS `Do Not Call`,
  577. SUM(CASE WHEN LS.`leadStatusId` = 20 THEN 1 ELSE 0 END) AS `Not Interested - General`,
  578. SUM(CASE WHEN LS.`leadStatusId` = 21 THEN 1 ELSE 0 END) AS `Over Age`,
  579. SUM(CASE WHEN LS.`leadStatusId` = 22 THEN 1 ELSE 0 END) AS `Not Interested - Already Insured`,
  580. SUM(CASE WHEN LS.`leadStatusId` = 23 THEN 1 ELSE 0 END) AS `Duplicate Data - Not Interested`,
  581. SUM(CASE WHEN LS.`leadStatusId` = 24 THEN 1 ELSE 0 END) AS `Not Eligible - PED`,
  582. SUM(CASE WHEN LS.`leadStatusId` = 25 THEN 1 ELSE 0 END) AS `Not Interested - Govt. Employee`,
  583. SUM(CASE WHEN LS.`leadStatusId` = 26 THEN 1 ELSE 0 END) AS `Not Interested - Senior Citizen`,
  584. SUM(CASE WHEN LS.`leadStatusId` = 27 THEN 1 ELSE 0 END) AS `Wrong Number`,
  585. SUM(CASE WHEN LS.`leadStatusId` = 28 THEN 1 ELSE 0 END) AS `Customer Not Available`,
  586. SUM(CASE WHEN LS.`leadStatusId` = 29 THEN 1 ELSE 0 END) AS `Language Barrier`,
  587. SUM(CASE WHEN LS.`leadStatusId` = 30 THEN 1 ELSE 0 END) AS `No Response`,
  588. SUM(CASE WHEN LS.`leadStatusId` = 33 THEN 1 ELSE 0 END) AS `Invalid Number`,
  589. SUM(CASE WHEN LS.`leadStatusId` = 36 THEN 1 ELSE 0 END) AS `Junk`,
  590. SUM(CASE WHEN LS.`leadStatusId` = 39 THEN 1 ELSE 0 END) AS `Ringing no response after five tries`,
  591. SUM(CASE WHEN LS.`leadStatusId` = 43 THEN 1 ELSE 0 END) AS `Switched Off/ Not Reachable after 5 tries`
  592. FROM `lead` join user on user.id=lead.currentAllocatedId left join leadStatus LS on LS.leadStatusId=lead.leadStatusId where lead.updatedOn >= "'.@$start.'" and lead.updatedOn <= "'.@$end.'" group by lead.currentAllocatedId';
  593. $esx = mysql_query($tableres) or die(mysql_error());
  594. $queryforinsert = "Insert into ".$table." (`Total Diposed`,`Sale Done`,`Follow Up`,`Do Not Call - Will Buy self on Website`,`Duplicate - Already In Talk With Team`,`In Contact with Oflline Agent`,`In Touch With Other Partner`,`Short Hangup`,`Call Later`,`Ringing Less Than Five Tries`,`Switched Off Less than Five Tries`,`Not Interested - Fund Problem`,`Just Checking Website`,`Not Interested - Insured From Employer`,`Not Interested - High Premium`,`Under Age`,`Not Visited Website`,`Do Not Call`,`Not Interested - General`,`Over Age`,`Not Interested - Already Insured`,`Duplicate Data - Not Interested`,`Not Eligible - PED`,`Not Interested - Govt. Employee`,`Not Interested - Senior Citizen`,`Wrong Number`,`Customer Not Available`,`Language Barrier`,`No Response`,`Invalid Number`,`Junk`,`Ringing no response after five tries`,`Switched Off/ Not Reachable after 5 tries`)
  595. select SUM(`Total Diposed`), SUM(`Sale Done`), SUM(`Follow Up`), SUM(`Do Not Call - Will Buy self on Website`), SUM(`Duplicate - Already In Talk With Team`), SUM(`In Contact with Oflline Agent`), SUM(`In Touch With Other Partner`), SUM(`Short Hangup`), SUM(`Call Later`), SUM(`Ringing Less Than Five Tries`), SUM(`Switched Off Less than Five Tries`), SUM(`Not Interested - Fund Problem`), SUM(`Just Checking Website`), SUM(`Not Interested - Insured From Employer`), SUM(`Not Interested - High Premium`), SUM(`Under Age`), SUM(`Not Visited Website`), SUM(`Do Not Call`), SUM(`Not Interested - General`), SUM(`Over Age`), SUM(`Not Interested - Already Insured`), SUM(`Duplicate Data - Not Interested`), SUM(`Not Eligible - PED`), SUM(`Not Interested - Govt. Employee`), SUM(`Not Interested - Senior Citizen`), SUM(`Wrong Number`), SUM(`Customer Not Available`), SUM(`Language Barrier`), SUM(`No Response`), SUM(`Invalid Number`), SUM(`Junk`), SUM(`Ringing no response after five tries`), SUM(`Switched Off/ Not Reachable after 5 tries`) from ".$table."";
  596. mysql_query($queryforinsert);
  597. $sql_query = "select * from $table";
  598. // Gets the data from the database
  599. $result = mysql_query($sql_query) or die(mysql_error());
  600. $fields_cnt = mysql_num_fields($result);
  601. $schema_insert = '';
  602. for ($i = 0; $i < $fields_cnt; $i++)
  603. {
  604. $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
  605. stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
  606. $schema_insert .= $l;
  607. $schema_insert .= $csv_separator;
  608. } // end for
  609. $out = trim(substr($schema_insert, 0, -1));
  610. $out .= $csv_terminated;
  611. // Format the data
  612. while ($row = mysql_fetch_array($result))
  613. {
  614. $schema_insert = '';
  615. for ($j = 0; $j < $fields_cnt; $j++)
  616. {
  617. if ($row[$j] == '0' || $row[$j] != '')
  618. {
  619. if ($csv_enclosed == '')
  620. {
  621. $schema_insert .= $row[$j];
  622. } else
  623. {
  624. $schema_insert .= $csv_enclosed .
  625. str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
  626. }
  627. } else
  628. {
  629. $schema_insert .= '';
  630. }
  631. if ($j < $fields_cnt - 1)
  632. {
  633. $schema_insert .= $csv_separator;
  634. }
  635. } // end for
  636. $out .= $schema_insert;
  637. $out .= $csv_terminated;
  638. } // end while
  639. /// header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  640. //header("Content-Length: " . strlen($out));
  641. // Output to browser with appropriate mime type, you choose ;)
  642. // header("Content-Disposition: attachment; filename=$filename");
  643. //header("Content-type: text/x-csv");
  644. $fd = fopen ($filename, "w");
  645. fputs($fd, $out);
  646. fclose($fd);
  647. echo "success";
  648. //header("Content-type: text/csv");
  649. //header("Content-type: application/csv");
  650. //echo $out;
  651. exit;
  652. }
  653. public function actionagentfreshleadsdisposition(){
  654. /* $date = date('d_M_Y')."_";
  655. $start = mktime(0, 0, 0);
  656. $end = mktime(23, 59, 59);
  657. */
  658. ini_set('max_input_time', 2400);
  659. ini_set('max_execution_time', 2400);
  660. $parser = new CHtmlPurifier();
  661. $afterMonth = $parser->purify(intval(@$_REQUEST['month']));
  662. $afterDate = $parser->purify(intval(@$_REQUEST['date']));
  663. $afterYear = $parser->purify(intval(@$_REQUEST['year']));
  664. if(isset($afterMonth) && !empty($afterMonth) && isset($afterDate) && !empty($afterDate) && isset($afterYear) && !empty($afterYear)){
  665. $start = mktime(0, 0, 0,$afterMonth,$afterDate,$afterYear);
  666. $end = mktime(23, 59, 59,$afterMonth,$afterDate,$afterYear);
  667. } else {
  668. $start = mktime(0, 0, 0);
  669. $end = mktime(23, 59, 59);
  670. }
  671. $time = time();
  672. $date = date('d_M_Y',$start).'_';
  673. $host = '10.216.6.59'; // MYSQL database host adress
  674. $db = 'lms'; // MYSQL database name
  675. $user = 'root'; // Mysql Datbase user
  676. $pass = '0kwp6aNR'; // Mysql Datbase password
  677. $link=mysql_connect($host,$user,$pass);
  678. mysql_select_db($db,$link);
  679. $table='report_agentfreshleadsdisposition';
  680. $filename = "filesystem/".$date.$table.'.csv';
  681. $csv_terminated = "\n";
  682. $csv_separator = ",";
  683. $csv_enclosed = '"';
  684. $csv_escaped = "\\";
  685. $time = time();
  686. mysql_query("insert into report_info (id,type,filename,createdOn,createdBy,updatedOn,updatedBy) values('','agentfreshleadsdisposition','".@$filename."','".@$time."','".@$_SESSION['id']."','".@$time."','".@$_SESSION['id']."')");
  687. $totalleadstatusids = '7,8,9,10,37,38,11,12,42,43,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,33,39,43';
  688. $chktableExist = mysql_query('DROP TABLE IF EXISTS '.$table.' ') or die(mysql_error());
  689. $tableres ='create table IF NOT EXISTS '.$table.' as SELECT
  690. user.userName as `Caller Name`,
  691. SUM(CASE WHEN lead.currentAllocatedId=user.id THEN 1 ELSE 0 END) AS `Total Assigned`,
  692. SUM(CASE WHEN lead.currentAllocatedId=user.id AND lead.leadStatusId NOT IN ('.@$totalleadstatusids.') THEN 1 ELSE 0 END) AS `No Update`,
  693. SUM(CASE WHEN lead.currentAllocatedId=user.id AND lead.leadStatusId IN ('.@$totalleadstatusids.') THEN 1 ELSE 0 END) AS `Total Diposed`,
  694. SUM(CASE WHEN LS.`leadStatusId` = 7 THEN 1 ELSE 0 END) AS `Sale Done`,
  695. SUM(CASE WHEN LS.`leadStatusId` = 8 THEN 1 ELSE 0 END) AS `Follow Up`,
  696. SUM(CASE WHEN LS.`leadStatusId` = 9 THEN 1 ELSE 0 END) AS `Do Not Call - Will Buy self on Website`,
  697. SUM(CASE WHEN LS.`leadStatusId` = 10 THEN 1 ELSE 0 END) AS `Duplicate - Already In Talk With Team`,
  698. SUM(CASE WHEN LS.`leadStatusId` = 37 THEN 1 ELSE 0 END) AS `In Contact with Oflline Agent`,
  699. SUM(CASE WHEN LS.`leadStatusId` = 38 THEN 1 ELSE 0 END) AS `In Touch With Other Partner`,
  700. SUM(CASE WHEN LS.`leadStatusId` = 11 THEN 1 ELSE 0 END) AS `Short Hangup`,
  701. SUM(CASE WHEN LS.`leadStatusId` = 12 THEN 1 ELSE 0 END) AS `Call Later`,
  702. SUM(CASE WHEN LS.`leadStatusId` = 42 THEN 1 ELSE 0 END) AS `Ringing Less Than Five Tries`,
  703. SUM(CASE WHEN LS.`leadStatusId` = 43 THEN 1 ELSE 0 END) AS `Switched Off Less than Five Tries`,
  704. SUM(CASE WHEN LS.`leadStatusId` = 13 THEN 1 ELSE 0 END) AS `Not Interested - Fund Problem`,
  705. SUM(CASE WHEN LS.`leadStatusId` = 14 THEN 1 ELSE 0 END) AS `Just Checking Website`,
  706. SUM(CASE WHEN LS.`leadStatusId` = 15 THEN 1 ELSE 0 END) AS `Not Interested - Insured From Employer`,
  707. SUM(CASE WHEN LS.`leadStatusId` = 16 THEN 1 ELSE 0 END) AS `Not Interested - High Premium`,
  708. SUM(CASE WHEN LS.`leadStatusId` = 17 THEN 1 ELSE 0 END) AS `Under Age`,
  709. SUM(CASE WHEN LS.`leadStatusId` = 18 THEN 1 ELSE 0 END) AS `Not Visited Website`,
  710. SUM(CASE WHEN LS.`leadStatusId` = 19 THEN 1 ELSE 0 END) AS `Do Not Call`,
  711. SUM(CASE WHEN LS.`leadStatusId` = 20 THEN 1 ELSE 0 END) AS `Not Interested - General`,
  712. SUM(CASE WHEN LS.`leadStatusId` = 21 THEN 1 ELSE 0 END) AS `Over Age`,
  713. SUM(CASE WHEN LS.`leadStatusId` = 22 THEN 1 ELSE 0 END) AS `Not Interested - Already Insured`,
  714. SUM(CASE WHEN LS.`leadStatusId` = 23 THEN 1 ELSE 0 END) AS `Duplicate Data - Not Interested`,
  715. SUM(CASE WHEN LS.`leadStatusId` = 24 THEN 1 ELSE 0 END) AS `Not Eligible - PED`,
  716. SUM(CASE WHEN LS.`leadStatusId` = 25 THEN 1 ELSE 0 END) AS `Not Interested - Govt. Employee`,
  717. SUM(CASE WHEN LS.`leadStatusId` = 26 THEN 1 ELSE 0 END) AS `Not Interested - Senior Citizen`,
  718. SUM(CASE WHEN LS.`leadStatusId` = 27 THEN 1 ELSE 0 END) AS `Wrong Number`,
  719. SUM(CASE WHEN LS.`leadStatusId` = 28 THEN 1 ELSE 0 END) AS `Customer Not Available`,
  720. SUM(CASE WHEN LS.`leadStatusId` = 29 THEN 1 ELSE 0 END) AS `Language Barrier`,
  721. SUM(CASE WHEN LS.`leadStatusId` = 30 THEN 1 ELSE 0 END) AS `No Response`,
  722. SUM(CASE WHEN LS.`leadStatusId` = 33 THEN 1 ELSE 0 END) AS `Invalid Number`,
  723. SUM(CASE WHEN LS.`leadStatusId` = 36 THEN 1 ELSE 0 END) AS `Junk`,
  724. SUM(CASE WHEN LS.`leadStatusId` = 39 THEN 1 ELSE 0 END) AS `Ringing no response after five tries`,
  725. SUM(CASE WHEN LS.`leadStatusId` = 43 THEN 1 ELSE 0 END) AS `Switched Off/ Not Reachable after 5 tries`
  726. FROM `lead` join user on user.id=lead.currentAllocatedId left join leadStatus LS on LS.leadStatusId=lead.leadStatusId where lead.leadStatusId !=36 AND lead.currentAllocatedDate >= "'.@$start.'" and lead.currentAllocatedDate <= "'.@$end.'" AND lead.leadId IN(select leadId from lead where lead.updatedOn >= "'.@$start.'" and lead.updatedOn <= "'.@$end.'" and lead.currentAllocatedDate >= "'.@$start.'" and lead.currentAllocatedDate <= "'.@$end.'" ) group by lead.currentAllocatedId';
  727. $esx = mysql_query($tableres) or die(mysql_error());
  728. $queryforinsert = "Insert into ".$table." (`Caller Name`,`Total Diposed`,`Sale Done`,`Follow Up`,`Do Not Call - Will Buy self on Website`,`Duplicate - Already In Talk With Team`,`In Contact with Oflline Agent`,`In Touch With Other Partner`,`Short Hangup`,`Call Later`,`Ringing Less Than Five Tries`,`Switched Off Less than Five Tries`,`Not Interested - Fund Problem`,`Just Checking Website`,`Not Interested - Insured From Employer`,`Not Interested - High Premium`,`Under Age`,`Not Visited Website`,`Do Not Call`,`Not Interested - General`,`Over Age`,`Not Interested - Already Insured`,`Duplicate Data - Not Interested`,`Not Eligible - PED`,`Not Interested - Govt. Employee`,`Not Interested - Senior Citizen`,`Wrong Number`,`Customer Not Available`,`Language Barrier`,`No Response`,`Invalid Number`,`Junk`,`Ringing no response after five tries`,`Switched Off/ Not Reachable after 5 tries`)
  729. select 'Total',SUM(`Total Diposed`), SUM(`Sale Done`), SUM(`Follow Up`), SUM(`Do Not Call - Will Buy self on Website`), SUM(`Duplicate - Already In Talk With Team`), SUM(`In Contact with Oflline Agent`), SUM(`In Touch With Other Partner`), SUM(`Short Hangup`), SUM(`Call Later`), SUM(`Ringing Less Than Five Tries`), SUM(`Switched Off Less than Five Tries`), SUM(`Not Interested - Fund Problem`), SUM(`Just Checking Website`), SUM(`Not Interested - Insured From Employer`), SUM(`Not Interested - High Premium`), SUM(`Under Age`), SUM(`Not Visited Website`), SUM(`Do Not Call`), SUM(`Not Interested - General`), SUM(`Over Age`), SUM(`Not Interested - Already Insured`), SUM(`Duplicate Data - Not Interested`), SUM(`Not Eligible - PED`), SUM(`Not Interested - Govt. Employee`), SUM(`Not Interested - Senior Citizen`), SUM(`Wrong Number`), SUM(`Customer Not Available`), SUM(`Language Barrier`), SUM(`No Response`), SUM(`Invalid Number`), SUM(`Junk`), SUM(`Ringing no response after five tries`), SUM(`Switched Off/ Not Reachable after 5 tries`) from ".$table."";
  730. mysql_query($queryforinsert);
  731. $sql_query = "select * from $table";
  732. // Gets the data from the database
  733. $result = mysql_query($sql_query);
  734. $fields_cnt = mysql_num_fields($result);
  735. $schema_insert = '';
  736. for ($i = 0; $i < $fields_cnt; $i++)
  737. {
  738. $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
  739. stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
  740. $schema_insert .= $l;
  741. $schema_insert .= $csv_separator;
  742. } // end for
  743. $out = trim(substr($schema_insert, 0, -1));
  744. $out .= $csv_terminated;
  745. // Format the data
  746. while ($row = mysql_fetch_array($result))
  747. {
  748. $schema_insert = '';
  749. for ($j = 0; $j < $fields_cnt; $j++)
  750. {
  751. if ($row[$j] == '0' || $row[$j] != '')
  752. {
  753. if ($csv_enclosed == '')
  754. {
  755. $schema_insert .= $row[$j];
  756. } else
  757. {
  758. $schema_insert .= $csv_enclosed .
  759. str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
  760. }
  761. } else
  762. {
  763. $schema_insert .= '';
  764. }
  765. if ($j < $fields_cnt - 1)
  766. {
  767. $schema_insert .= $csv_separator;
  768. }
  769. } // end for
  770. $out .= $schema_insert;
  771. $out .= $csv_terminated;
  772. } // end while
  773. $fd = fopen ($filename, "w");
  774. fputs($fd, $out);
  775. fclose($fd);
  776. echo "success";
  777. //header("Content-type: text/csv");
  778. //header("Content-type: application/csv");
  779. //echo $out;
  780. exit;
  781. }
  782. public function actionagentfreshleadsdisposition_30thOct2014(){
  783. ini_set('max_input_time', 1200);
  784. ini_set('max_execution_time', 1200);
  785. $date = date('d_M_Y')."_";
  786. $host = '10.216.6.59'; // MYSQL database host adress
  787. $db = 'lms'; // MYSQL database name
  788. $user = 'root'; // Mysql Datbase user
  789. $pass = '0kwp6aNR'; // Mysql Datbase password
  790. $link=mysql_connect($host,$user,$pass);
  791. mysql_select_db($db,$link);
  792. $table='report_agentfreshleadsdisposition';
  793. $filename = "filesystem/".$date.$table.'.csv';
  794. $csv_terminated = "\n";
  795. $csv_separator = ",";
  796. $csv_enclosed = '"';
  797. $csv_escaped = "\\";
  798. $time = time();
  799. mysql_query("insert into report_info (id,type,filename,createdOn,createdBy,updatedOn,updatedBy) values('','agentfreshleadsdisposition','".@$filename."','".@$time."','0','".@$time."','0')");
  800. $chktableExist = mysql_query('DROP TABLE IF EXISTS '.$table.' ') or die(mysql_error());
  801. $tableres ='create table IF NOT EXISTS '.$table.' as SELECT
  802. user.userName as `Caller Name`,
  803. SUM(CASE WHEN lead.currentAllocatedId=user.id THEN 1 ELSE 0 END) AS `Total Diposed`,
  804. SUM(CASE WHEN LS.`leadStatusId` = 7 THEN 1 ELSE 0 END) AS `Sale Done`,
  805. SUM(CASE WHEN LS.`leadStatusId` = 8 THEN 1 ELSE 0 END) AS `Follow Up`,
  806. SUM(CASE WHEN LS.`leadStatusId` = 9 THEN 1 ELSE 0 END) AS `Do Not Call - Will Buy self on Website`,
  807. SUM(CASE WHEN LS.`leadStatusId` = 10 THEN 1 ELSE 0 END) AS `Duplicate - Already In Talk With Team`,
  808. SUM(CASE WHEN LS.`leadStatusId` = 37 THEN 1 ELSE 0 END) AS `In Contact with Oflline Agent`,
  809. SUM(CASE WHEN LS.`leadStatusId` = 38 THEN 1 ELSE 0 END) AS `In Touch With Other Partner`,
  810. SUM(CASE WHEN LS.`leadStatusId` = 11 THEN 1 ELSE 0 END) AS `Short Hangup`,
  811. SUM(CASE WHEN LS.`leadStatusId` = 12 THEN 1 ELSE 0 END) AS `Call Later`,
  812. SUM(CASE WHEN LS.`leadStatusId` = 42 THEN 1 ELSE 0 END) AS `Ringing Less Than Five Tries`,
  813. SUM(CASE WHEN LS.`leadStatusId` = 43 THEN 1 ELSE 0 END) AS `Switched Off Less than Five Tries`,
  814. SUM(CASE WHEN LS.`leadStatusId` = 13 THEN 1 ELSE 0 END) AS `Not Interested - Fund Problem`,
  815. SUM(CASE WHEN LS.`leadStatusId` = 14 THEN 1 ELSE 0 END) AS `Just Checking Website`,
  816. SUM(CASE WHEN LS.`leadStatusId` = 15 THEN 1 ELSE 0 END) AS `Not Interested - Insured From Employer`,
  817. SUM(CASE WHEN LS.`leadStatusId` = 16 THEN 1 ELSE 0 END) AS `Not Interested - High Premium`,
  818. SUM(CASE WHEN LS.`leadStatusId` = 17 THEN 1 ELSE 0 END) AS `Under Age`,
  819. SUM(CASE WHEN LS.`leadStatusId` = 18 THEN 1 ELSE 0 END) AS `Not Visited Website`,
  820. SUM(CASE WHEN LS.`leadStatusId` = 19 THEN 1 ELSE 0 END) AS `Do Not Call`,
  821. SUM(CASE WHEN LS.`leadStatusId` = 20 THEN 1 ELSE 0 END) AS `Not Interested - General`,
  822. SUM(CASE WHEN LS.`leadStatusId` = 21 THEN 1 ELSE 0 END) AS `Over Age`,
  823. SUM(CASE WHEN LS.`leadStatusId` = 22 THEN 1 ELSE 0 END) AS `Not Interested - Already Insured`,
  824. SUM(CASE WHEN LS.`leadStatusId` = 23 THEN 1 ELSE 0 END) AS `Duplicate Data - Not Interested`,
  825. SUM(CASE WHEN LS.`leadStatusId` = 24 THEN 1 ELSE 0 END) AS `Not Eligible - PED`,
  826. SUM(CASE WHEN LS.`leadStatusId` = 25 THEN 1 ELSE 0 END) AS `Not Interested - Govt. Employee`,
  827. SUM(CASE WHEN LS.`leadStatusId` = 26 THEN 1 ELSE 0 END) AS `Not Interested - Senior Citizen`,
  828. SUM(CASE WHEN LS.`leadStatusId` = 27 THEN 1 ELSE 0 END) AS `Wrong Number`,
  829. SUM(CASE WHEN LS.`leadStatusId` = 28 THEN 1 ELSE 0 END) AS `Customer Not Available`,
  830. SUM(CASE WHEN LS.`leadStatusId` = 29 THEN 1 ELSE 0 END) AS `Language Barrier`,
  831. SUM(CASE WHEN LS.`leadStatusId` = 30 THEN 1 ELSE 0 END) AS `No Response`,
  832. SUM(CASE WHEN LS.`leadStatusId` = 33 THEN 1 ELSE 0 END) AS `Invalid Number`,
  833. SUM(CASE WHEN LS.`leadStatusId` = 36 THEN 1 ELSE 0 END) AS `Junk`,
  834. SUM(CASE WHEN LS.`leadStatusId` = 39 THEN 1 ELSE 0 END) AS `Ringing no response after five tries`,
  835. SUM(CASE WHEN LS.`leadStatusId` = 43 THEN 1 ELSE 0 END) AS `Switched Off/ Not Reachable after 5 tries`
  836. FROM `lead` join user on user.id=lead.currentAllocatedId left join leadStatus LS on LS.leadStatusId=lead.leadStatusId where lead.leadStatusId = 34 AND lead.currentAllocatedId<1 group by lead.currentAllocatedId';
  837. $esx = mysql_query($tableres) or die(mysql_error());
  838. $queryforinsert = "Insert into ".$table." (`Total Diposed`,`Sale Done`,`Follow Up`,`Do Not Call - Will Buy self on Website`,`Duplicate - Already In Talk With Team`,`In Contact with Oflline Agent`,`In Touch With Other Partner`,`Short Hangup`,`Call Later`,`Ringing Less Than Five Tries`,`Switched Off Less than Five Tries`,`Not Interested - Fund Problem`,`Just Checking Website`,`Not Interested - Insured From Employer`,`Not Interested - High Premium`,`Under Age`,`Not Visited Website`,`Do Not Call`,`Not Interested - General`,`Over Age`,`Not Interested - Already Insured`,`Duplicate Data - Not Interested`,`Not Eligible - PED`,`Not Interested - Govt. Employee`,`Not Interested - Senior Citizen`,`Wrong Number`,`Customer Not Available`,`Language Barrier`,`No Response`,`Invalid Number`,`Junk`,`Ringing no response after five tries`,`Switched Off/ Not Reachable after 5 tries`)
  839. select SUM(`Total Diposed`), SUM(`Sale Done`), SUM(`Follow Up`), SUM(`Do Not Call - Will Buy self on Website`), SUM(`Duplicate - Already In Talk With Team`), SUM(`In Contact with Oflline Agent`), SUM(`In Touch With Other Partner`), SUM(`Short Hangup`), SUM(`Call Later`), SUM(`Ringing Less Than Five Tries`), SUM(`Switched Off Less than Five Tries`), SUM(`Not Interested - Fund Problem`), SUM(`Just Checking Website`), SUM(`Not Interested - Insured From Employer`), SUM(`Not Interested - High Premium`), SUM(`Under Age`), SUM(`Not Visited Website`), SUM(`Do Not Call`), SUM(`Not Interested - General`), SUM(`Over Age`), SUM(`Not Interested - Already Insured`), SUM(`Duplicate Data - Not Interested`), SUM(`Not Eligible - PED`), SUM(`Not Interested - Govt. Employee`), SUM(`Not Interested - Senior Citizen`), SUM(`Wrong Number`), SUM(`Customer Not Available`), SUM(`Language Barrier`), SUM(`No Response`), SUM(`Invalid Number`), SUM(`Junk`), SUM(`Ringing no response after five tries`), SUM(`Switched Off/ Not Reachable after 5 tries`) from ".$table."";
  840. mysql_query($queryforinsert);
  841. $sql_query = "select * from $table";
  842. // Gets the data from the database
  843. $result = mysql_query($sql_query);
  844. $fields_cnt = mysql_num_fields($result);
  845. $schema_insert = '';
  846. for ($i = 0; $i < $fields_cnt; $i++)
  847. {
  848. $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
  849. stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
  850. $schema_insert .= $l;
  851. $schema_insert .= $csv_separator;
  852. } // end for
  853. $out = trim(substr($schema_insert, 0, -1));
  854. $out .= $csv_terminated;
  855. // Format the data
  856. while ($row = mysql_fetch_array($result))
  857. {
  858. $schema_insert = '';
  859. for ($j = 0; $j < $fields_cnt; $j++)
  860. {
  861. if ($row[$j] == '0' || $row[$j] != '')
  862. {
  863. if ($csv_enclosed == '')
  864. {
  865. $schema_insert .= $row[$j];
  866. } else
  867. {
  868. $schema_insert .= $csv_enclosed .
  869. str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
  870. }
  871. } else
  872. {
  873. $schema_insert .= '';
  874. }
  875. if ($j < $fields_cnt - 1)
  876. {
  877. $schema_insert .= $csv_separator;
  878. }
  879. } // end for
  880. $out .= $schema_insert;
  881. $out .= $csv_terminated;
  882. } // end while
  883. $fd = fopen ($filename, "w");
  884. fputs($fd, $out);
  885. fclose($fd);
  886. echo "success";
  887. //header("Content-type: text/csv");
  888. //header("Content-type: application/csv");
  889. //echo $out;
  890. exit;
  891. }
  892. public function actioncampaignwisedispositiondaily(){
  893. ini_set('max_input_time', 1200);
  894. ini_set('max_execution_time', 1200);
  895. $time = time();
  896. $parser = new CHtmlPurifier();
  897. $afterMonth = $parser->purify(intval(@$_REQUEST['month']));
  898. $afterDate = $parser->purify(intval(@$_REQUEST['date']));
  899. $afterYear = $parser->purify(intval(@$_REQUEST['year']));
  900. if(isset($afterMonth) && !empty($afterMonth) && isset($afterDate) && !empty($afterDate) && isset($afterYear) && !empty($afterYear)){
  901. $start = mktime(0, 0, 0,$afterMonth,$afterDate,$afterYear);
  902. $end = mktime(23, 59, 59,$afterMonth,$afterDate,$afterYear);
  903. } else {
  904. $start = mktime(0, 0, 0);
  905. $end = mktime(23, 59, 59);
  906. }
  907. $date = date('d_M_Y',$start)."_";
  908. $host = '10.216.6.59'; // MYSQL database host adress
  909. $db = 'lms'; // MYSQL database name
  910. $user = 'root'; // Mysql Datbase user
  911. $pass = '0kwp6aNR'; // Mysql Datbase password
  912. $link=mysql_connect($host,$user,$pass);
  913. mysql_select_db($db,$link);
  914. $table='report_campaignwisedispositiondaily';
  915. $filename = "filesystem/".$date.$table.'.csv';
  916. $csv_terminated = "\n";
  917. $csv_separator = ",";
  918. $csv_enclosed = '"';
  919. $csv_escaped = "\\";
  920. mysql_query("insert into report_info (id,type,filename,createdOn,createdBy,updatedOn,updatedBy) values('','campaignwisedispositiondaily','".@$filename."','".@$time."','0','".@$time."','0')");
  921. $chktableExist = mysql_query('DROP TABLE IF EXISTS '.$table.' ') or die(mysql_error());
  922. $tableres ='create table IF NOT EXISTS '.$table.' as SELECT LS.leadSourceCode as `Agent Code`,LS.leadSourceTitle as `Name`,count(L.ws_agentid) as `Total Diposed`,
  923. SUM(CASE WHEN L.`leadStatusId` = 7 THEN 1 ELSE 0 END) AS `Sale Done`,
  924. SUM(CASE WHEN L.`leadStatusId` = 8 THEN 1 ELSE 0 END) AS `Follow Up`,
  925. SUM(CASE WHEN L.`leadStatusId` = 9 THEN 1 ELSE 0 END) AS `Do Not Call - Will Buy self on Website`,
  926. SUM(CASE WHEN L.`leadStatusId` = 10 THEN 1 ELSE 0 END) AS `Duplicate - Already In Talk With Team`,
  927. SUM(CASE WHEN L.`leadStatusId` = 37 THEN 1 ELSE 0 END) AS `In Contact with Oflline Agent`,
  928. SUM(CASE WHEN L.`leadStatusId` = 38 THEN 1 ELSE 0 END) AS `In Touch With Other Partner`,
  929. SUM(CASE WHEN L.`leadStatusId` = 11 THEN 1 ELSE 0 END) AS `Short Hangup`,
  930. SUM(CASE WHEN L.`leadStatusId` = 12 THEN 1 ELSE 0 END) AS `Call Later`,
  931. SUM(CASE WHEN L.`leadStatusId` = 42 THEN 1 ELSE 0 END) AS `Ringing Less Than Five Tries`,
  932. SUM(CASE WHEN L.`leadStatusId` = 43 THEN 1 ELSE 0 END) AS `Switched Off Less than Five Tries`,
  933. SUM(CASE WHEN L.`leadStatusId` = 13 THEN 1 ELSE 0 END) AS `Not Interested - Fund Problem`,
  934. SUM(CASE WHEN L.`leadStatusId` = 14 THEN 1 ELSE 0 END) AS `Just Checking Website`,
  935. SUM(CASE WHEN L.`leadStatusId` = 15 THEN 1 ELSE 0 END) AS `Not Interested - Insured From Employer`,
  936. SUM(CASE WHEN L.`leadStatusId` = 16 THEN 1 ELSE 0 END) AS `Not Interested - High Premium`,
  937. SUM(CASE WHEN L.`leadStatusId` = 17 THEN 1 ELSE 0 END) AS `Under Age`,
  938. SUM(CASE WHEN L.`leadStatusId` = 18 THEN 1 ELSE 0 END) AS `Not Visited Website`,
  939. SUM(CASE WHEN L.`leadStatusId` = 19 THEN 1 ELSE 0 END) AS `Do Not Call`,
  940. SUM(CASE WHEN L.`leadStatusId` = 20 THEN 1 ELSE 0 END) AS `Not Interested - General`,
  941. SUM(CASE WHEN L.`leadStatusId` = 21 THEN 1 ELSE 0 END) AS `Over Age`,
  942. SUM(CASE WHEN L.`leadStatusId` = 22 THEN 1 ELSE 0 END) AS `Not Interested - Already Insured`,
  943. SUM(CASE WHEN L.`leadStatusId` = 23 THEN 1 ELSE 0 END) AS `Duplicate Data - Not Interested`,
  944. SUM(CASE WHEN L.`leadStatusId` = 24 THEN 1 ELSE 0 END) AS `Not Eligible - PED`,
  945. SUM(CASE WHEN L.`leadStatusId` = 25 THEN 1 ELSE 0 END) AS `Not Interested - Govt. Employee`,
  946. SUM(CASE WHEN L.`leadStatusId` = 26 THEN 1 ELSE 0 END) AS `Not Interested - Senior Citizen`,
  947. SUM(CASE WHEN L.`leadStatusId` = 27 THEN 1 ELSE 0 END) AS `Wrong Number`,
  948. SUM(CASE WHEN L.`leadStatusId` = 28 THEN 1 ELSE 0 END) AS `Customer Not Available`,
  949. SUM(CASE WHEN L.`leadStatusId` = 29 THEN 1 ELSE 0 END) AS `Language Barrier`,
  950. SUM(CASE WHEN L.`leadStatusId` = 30 THEN 1 ELSE 0 END) AS `No Response`,
  951. SUM(CASE WHEN L.`leadStatusId` = 33 THEN 1 ELSE 0 END) AS `Invalid Number`,
  952. SUM(CASE WHEN L.`leadStatusId` = 36 THEN 1 ELSE 0 END) AS `Junk`,
  953. SUM(CASE WHEN L.`leadStatusId` = 39 THEN 1 ELSE 0 END) AS `Ringing no response after five tries`,
  954. SUM(CASE WHEN L.`leadStatusId` = 43 THEN 1 ELSE 0 END) AS `Switched Off/ Not Reachable after 5 tries`
  955. from leadSourceMaster LS left join lead L on L.ws_agentid=LS.leadSourceCode where L.updatedOn >= "'.@$start.'" and L.updatedOn <= "'.@$end.'" group by L.leadStatusId,LS.leadSourceCode';
  956. $esx = mysql_query($tableres) or die(mysql_error());
  957. $queryforinsert = "Insert into ".$table." (`Total Diposed`,`Sale Done`,`Follow Up`,`Do Not Call - Will Buy self on Website`,`Duplicate - Already In Talk With Team`,`In Contact with Oflline Agent`,`In Touch With Other Partner`,`Short Hangup`,`Call Later`,`Ringing Less Than Five Tries`,`Switched Off Less than Five Tries`,`Not Interested - Fund Problem`,`Just Checking Website`,`Not Interested - Insured From Employer`,`Not Interested - High Premium`,`Under Age`,`Not Visited Website`,`Do Not Call`,`Not Interested - General`,`Over Age`,`Not Interested - Already Insured`,`Duplicate Data - Not Interested`,`Not Eligible - PED`,`Not Interested - Govt. Employee`,`Not Interested - Senior Citizen`,`Wrong Number`,`Customer Not Available`,`Language Barrier`,`No Response`,`Invalid Number`,`Junk`,`Ringing no response after five tries`,`Switched Off/ Not Reachable after 5 tries`)
  958. select SUM(`Total Diposed`), SUM(`Sale Done`), SUM(`Follow Up`), SUM(`Do Not Call - Will Buy self on Website`), SUM(`Duplicate - Already In Talk With Team`), SUM(`In Contact with Oflline Agent`), SUM(`In Touch With Other Partner`), SUM(`Short Hangup`), SUM(`Call Later`), SUM(`Ringing Less Than Five Tries`), SUM(`Switched Off Less than Five Tries`), SUM(`Not Interested - Fund Problem`), SUM(`Just Checking Website`), SUM(`Not Interested - Insured From Employer`), SUM(`Not Interested - High Premium`), SUM(`Under Age`), SUM(`Not Visited Website`), SUM(`Do Not Call`), SUM(`Not Interested - General`), SUM(`Over Age`), SUM(`Not Interested - Already Insured`), SUM(`Duplicate Data - Not Interested`), SUM(`Not Eligible - PED`), SUM(`Not Interested - Govt. Employee`), SUM(`Not Interested - Senior Citizen`), SUM(`Wrong Number`), SUM(`Customer Not Available`), SUM(`Language Barrier`), SUM(`No Response`), SUM(`Invalid Number`), SUM(`Junk`), SUM(`Ringing no response after five tries`), SUM(`Switched Off/ Not Reachable after 5 tries`) from ".$table."";
  959. mysql_query($queryforinsert);
  960. $sql_query = "select * from ".$table."";
  961. // Gets the data from the database
  962. $result = mysql_query($sql_query);
  963. $fields_cnt = mysql_num_fields($result);
  964. $schema_insert = '';
  965. for ($i = 0; $i < $fields_cnt; $i++)
  966. {
  967. $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
  968. stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
  969. $schema_insert .= $l;
  970. $schema_insert .= $csv_separator;
  971. } // end for
  972. $out = trim(substr($schema_insert, 0, -1));
  973. $out .= $csv_terminated;
  974. // Format the data
  975. while ($row = mysql_fetch_array($result))
  976. {
  977. $schema_insert = '';
  978. for ($j = 0; $j < $fields_cnt; $j++)
  979. {
  980. if ($row[$j] == '0' || $row[$j] != '')
  981. {
  982. if ($csv_enclosed == '')
  983. {
  984. $schema_insert .= $row[$j];
  985. } else
  986. {
  987. $schema_insert .= $csv_enclosed .
  988. str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
  989. }
  990. } else
  991. {
  992. $schema_insert .= '';
  993. }
  994. if ($j < $fields_cnt - 1)
  995. {
  996. $schema_insert .= $csv_separator;
  997. }
  998. } // end for
  999. $out .= $schema_insert;
  1000. $out .= $csv_terminated;
  1001. } // end while
  1002. $fd = fopen ($filename, "w");
  1003. fputs($fd, $out);
  1004. fclose($fd);
  1005. echo "success";
  1006. //header("Content-type: text/csv");
  1007. //header("Content-type: application/csv");
  1008. //echo $out;
  1009. exit;
  1010. }
  1011. public function actiondatadumpsameday(){
  1012. ini_set('max_input_time', 1200);
  1013. ini_set('max_execution_time', 1200);
  1014. $parser = new CHtmlPurifier();
  1015. $afterMonth = $parser->purify(intval(@$_REQUEST['month']));
  1016. $afterDate = $parser->purify(intval(@$_REQUEST['date']));
  1017. $afterYear = $parser->purify(intval(@$_REQUEST['year']));
  1018. if(isset($afterMonth) && !empty($afterMonth) && isset($afterDate) && !empty($afterDate) && isset($afterYear) && !empty($afterYear)){
  1019. $start = mktime(0, 0, 0,$afterMonth,$afterDate,$afterYear);
  1020. $end = mktime(23, 59, 59,$afterMonth,$afterDate,$afterYear);
  1021. } else {
  1022. $start = mktime(0, 0, 0);
  1023. $end = mktime(23, 59, 59);
  1024. }
  1025. $time = time();
  1026. $date = date('d_M_Y',$start).'_';
  1027. $host = '10.216.6.59'; // MYSQL database host adress
  1028. $db = 'lms'; // MYSQL database name
  1029. $user = 'root'; // Mysql Datbase user
  1030. $pass = '0kwp6aNR'; // Mysql Datbase password
  1031. $link=mysql_connect($host,$user,$pass);
  1032. mysql_select_db($db,$link);
  1033. $table='report_datadumpsameday';
  1034. $filename = "filesystem/".$date.$table.'.csv';
  1035. $csv_terminated = "\n";
  1036. $csv_separator = ",";
  1037. $csv_enclosed = '"';
  1038. $csv_escaped = "\\";
  1039. mysql_query("insert into report_info (id,type,filename,createdOn,createdBy,updatedOn,updatedBy) values('','datadumpsameday','".@$filename."','".@$time."','".@$_SESSION['id']."','".@$time."','".@$_SESSION['id']."')");
  1040. $chktableExist = mysql_query('DROP TABLE IF EXISTS '.$table.' ') or die(mysql_error());
  1041. mysql_query('set @a:=0');
  1042. $tableres ="create table IF NOT EXISTS ".$table." as select @a:=@a+1 `Sr.no`,L.mobile as `mobile`,from_unixtime(L.createdOn, '%Y/%m/%d') as `Lead Creat Date`,from_unixtime(L.createdOn, '%h:%i:%s %p') as `Lead created Time`,IF((L.currentAllocatedDate='' or L.currentAllocatedDate=0),0,from_unixtime(L.currentAllocatedDate, '%Y/%m/%d')) as `Lead Assign Date`,IF((L.currentAllocatedDate='' or L.currentAllocatedDate=0),0,from_unixtime(L.currentAllocatedDate, '%h:%i:%s %p')) as `Lead Assign Time`,LS.LeadsourceTitle as `Agent Name`,L.ws_agentId as `Agent Code`,CG.campaignName as `Campagin Name`,LSS.leadStatus as `Disposition`,L.leadDescription as `Remarks` from lead L left join leadSourceMaster LS on LS.leadSourceCode=L.ws_agentid left join campaign CG on CG.campaignId=L.campaignId left join leadStatus LSS on LSS.leadstatusId=L.leadStatusId where L.leadStatusId !=36 AND L.createdOn >= '".@$start."' and L.createdOn <= '".@$end."'";
  1043. //$tableres ="create table IF NOT EXISTS ".$table." as select @a:=@a+1 `Sr.no`,L.mobile as `mobile`,from_unixtime(L.createdOn, '%Y/%m/%d') as `Lead Creat Date`,from_unixtime(L.createdOn, '%h:%i:%s %p') as `Lead created Time`,IF(L.currentAllocatedDate='',0,from_unixtime(L.currentAllocatedDate, '%Y/%m/%d')) as `Lead Assign Date`,IF(L.currentAllocatedDate='',0,from_unixtime(L.currentAllocatedDate, '%h:%i:%s %p')) as `Lead Assign Time`,LS.LeadsourceTitle as `Agent Name`,L.ws_agentId as `Agent Code`,CG.campaignName as `Campagin Name`,LSS.leadStatus as `Disposition`,L.leadDescription as `Remarks` from lead L left join leadSourceMaster LS on LS.leadSourceCode=L.ws_agentid left join campaign CG on CG.campaignId=L.campaignId left join leadStatus LSS on LSS.leadstatusId=L.leadStatusId where L.leadStatusId !=36 AND L.createdOn >= '".@$start."' and L.createdOn <= '".@$end."'";
  1044. $esx = mysql_query($tableres) or die(mysql_error());
  1045. $sql_query = "select * from $table";
  1046. // Gets the data from the database
  1047. $result = mysql_query($sql_query);
  1048. $fields_cnt = mysql_num_fields($result);
  1049. $schema_insert = '';
  1050. for ($i = 0; $i < $fields_cnt; $i++)
  1051. {
  1052. $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
  1053. stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
  1054. $schema_insert .= $l;
  1055. $schema_insert .= $csv_separator;
  1056. } // end for
  1057. $out = trim(substr($schema_insert, 0, -1));
  1058. $out .= $csv_terminated;
  1059. // Format the data
  1060. while ($row = mysql_fetch_array($result))
  1061. {
  1062. $schema_insert = '';
  1063. for ($j = 0; $j < $fields_cnt; $j++)
  1064. {
  1065. if ($row[$j] == '0' || $row[$j] != '')
  1066. {
  1067. if ($csv_enclosed == '')
  1068. {
  1069. $schema_insert .= $row[$j];
  1070. } else
  1071. {
  1072. $schema_insert .= $csv_enclosed .
  1073. str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
  1074. }
  1075. } else
  1076. {
  1077. $schema_insert .= '';
  1078. }
  1079. if ($j < $fields_cnt - 1)
  1080. {
  1081. $schema_insert .= $csv_separator;
  1082. }
  1083. } // end for
  1084. $out .= $schema_insert;
  1085. $out .= $csv_terminated;
  1086. } // end while
  1087. $fd = fopen ($filename, "w");
  1088. fputs($fd, $out);
  1089. fclose($fd);
  1090. echo "success";
  1091. //header("Content-type: text/csv");
  1092. //header("Content-type: application/csv");
  1093. //echo $out;
  1094. exit;
  1095. }
  1096. public function actiondatadumpmtd(){
  1097. ini_set('max_input_time', 19200);
  1098. ini_set('max_execution_time', 19200);
  1099. $parser = new CHtmlPurifier();
  1100. $afterMonth = $parser->purify(intval(@$_REQUEST['month']));
  1101. $afterYear = $parser->purify(intval(@$_REQUEST['year']));
  1102. if(isset($afterMonth) && !empty($afterMonth) && isset($afterYear) && !empty($afterYear)){
  1103. $start =mktime(0, 0, 0, $afterMonth, 1,$afterYear);
  1104. $end = mktime(23, 59, 0, $afterMonth, date('t', $start),$afterYear);
  1105. } else {
  1106. $start = strtotime('first day of this month', time());
  1107. $end = strtotime('last day of this month', time());
  1108. }
  1109. $date = date('d_M_Y',$start).'_';
  1110. $host = '10.216.6.59'; // MYSQL database host adress
  1111. $db = 'lms'; // MYSQL database name
  1112. $user = 'root'; // Mysql Datbase user
  1113. $pass = '0kwp6aNR'; // Mysql Datbase password
  1114. $link=mysql_connect($host,$user,$pass);
  1115. mysql_select_db($db,$link);
  1116. $table='report_datadumpmtd';
  1117. $filename = "filesystem/".$date.$table.'.csv';
  1118. $csv_terminated = "\n";
  1119. $csv_separator = ",";
  1120. $csv_enclosed = '"';
  1121. $csv_escaped = "\\";
  1122. $time = time();
  1123. mysql_query("insert into report_info (id,type,filename,createdOn,createdBy,updatedOn,updatedBy) values('','datadumpmtd','".@$filename."','".@$time."','0','".@$time."','0')");
  1124. $chktableExist = mysql_query('DROP TABLE IF EXISTS '.$table.' ') or die(mysql_error());
  1125. mysql_query('set @a:=0');
  1126. $tableres ="create table IF NOT EXISTS ".$table." as select @a:=@a+1 `Sr.no`,L.mobile as `mobile`,from_unixtime(L.createdOn, '%Y/%m/%d') as `Lead Creat Date`,from_unixtime(L.createdOn, '%h:%i:%s %p') as `Lead created Time`,IF(L.currentAllocatedDate='',0,from_unixtime(L.currentAllocatedDate, '%Y/%m/%d')) as `Lead Assign Date`,IF(L.currentAllocatedDate='',0,from_unixtime(L.currentAllocatedDate, '%h:%i:%s %p')) as `Lead Assign Time`,LS.LeadsourceTitle as `Agent Name`,L.ws_agentId as `Agent Code`,CG.campaignName as `Campagin Name`,LSS.leadStatus as `Disposition`,L.leadDescription as `Remarks` from lead L left join leadSourceMaster LS on LS.leadSourceCode=L.ws_agentid left join campaign CG on CG.campaignId=L.campaignId left join leadStatus LSS on LSS.leadstatusId=L.leadStatusId where L.leadStatusId !=36 AND L.updatedOn >= '".@$start."' and L.updatedOn <= '".@$end."'";
  1127. $esx = mysql_query($tableres) or die(mysql_error());
  1128. $sql_query = "select * from $table";
  1129. // Gets the data from the database
  1130. $result = mysql_query($sql_query);
  1131. $fields_cnt = mysql_num_fields($result);
  1132. $schema_insert = '';
  1133. for ($i = 0; $i < $fields_cnt; $i++)
  1134. {
  1135. $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
  1136. stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
  1137. $schema_insert .= $l;
  1138. $schema_insert .= $csv_separator;
  1139. } // end for
  1140. $out = trim(substr($schema_insert, 0, -1));
  1141. $out .= $csv_terminated;
  1142. // Format the data
  1143. while ($row = mysql_fetch_array($result))
  1144. {
  1145. $schema_insert = '';
  1146. for ($j = 0; $j < $fields_cnt; $j++)
  1147. {
  1148. if ($row[$j] == '0' || $row[$j] != '')
  1149. {
  1150. if ($csv_enclosed == '')
  1151. {
  1152. $schema_insert .= $row[$j];
  1153. } else
  1154. {
  1155. $schema_insert .= $csv_enclosed .
  1156. str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
  1157. }
  1158. } else
  1159. {
  1160. $schema_insert .= '';
  1161. }
  1162. if ($j < $fields_cnt - 1)
  1163. {
  1164. $schema_insert .= $csv_separator;
  1165. }
  1166. } // end for
  1167. $out .= $schema_insert;
  1168. $out .= $csv_terminated;
  1169. } // end while
  1170. $fd = fopen ($filename, "w");
  1171. fputs($fd, $out);
  1172. fclose($fd);
  1173. echo "success";
  1174. //header("Content-type: text/csv");
  1175. //header("Content-type: application/csv");
  1176. //echo $out;
  1177. exit;
  1178. }
  1179. public function actionreporttest(){
  1180. $maxDays=date('t');
  1181. ini_set('max_input_time', 1200);
  1182. ini_set('max_execution_time', 1200);
  1183. $date = date('d_M_Y').'_';
  1184. $host = '10.216.6.59'; // MYSQL database host adress
  1185. $db = 'lms'; // MYSQL database name
  1186. $user = 'root'; // Mysql Datbase user
  1187. $pass = '0kwp6aNR'; // Mysql Datbase password
  1188. $link=mysql_connect($host,$user,$pass);
  1189. mysql_select_db($db,$link);
  1190. $table='report_datadumpmtd';
  1191. $query = mysql_query("select leadSourceCode,leadSourceTitle from leadSourceMaster") ;
  1192. $columnName = array();
  1193. $l=0;
  1194. while($l= mysql_fetch_array($query)){
  1195. $columnName[] = $l['leadSourceCode'];
  1196. $columnNameData[] = $l['leadSourceCode'];
  1197. $leadSourceName[] = $l['leadSourceTitle'];
  1198. $l++;
  1199. }
  1200. $columnName=implode(',',$columnName);
  1201. $leadSourceName=implode(',',$leadSourceName);
  1202. if(count($l)>0){
  1203. $file_name = "lms" . "_" . date("Y-m-d_H-i", time()) . ".csv";
  1204. header('Content-Type: text/html; charset=utf-8');
  1205. header("Content-type: application/octet-stream");
  1206. header("Content-Disposition: attachment; filename=\"$file_name\"");
  1207. header("Cache-Control: cache, must-revalidate");
  1208. header("Pragma: public");
  1209. $col = array(
  1210. 'Agent Code','Total',$columnName);
  1211. foreach ($col as $key => $value) {
  1212. echo $value . ",";
  1213. }
  1214. echo "\n";
  1215. $col2 = array(
  1216. 'Agent Name','',$leadSourceName);
  1217. foreach ($col2 as $key => $value) {
  1218. echo $value . ",";
  1219. }
  1220. echo "\n";
  1221. $i=2;
  1222. $col3 = array($columnNameData);
  1223. $f=0;
  1224. $neresult = 0;
  1225. for($y=1;$y<=$maxDays;$y++) {
  1226. $date = $y.date('/m/Y');
  1227. $explodedDate = explode('/',$date);
  1228. $time = strtotime($explodedDate[0]."-".$explodedDate[1]."-".$explodedDate[2]);
  1229. $timePm = strtotime($explodedDate[0]."-".$explodedDate[1]."-".$explodedDate[2])+86399;
  1230. echo $y.date('/M/Y'). ",";
  1231. $quert = mysql_query('select count(*) as total from lead where ws_agentId IN( "'.@$value[0].'","'.@$value[1].'") and updatedOn >= "'.@$time.'" and updatedOn <= "'.@$timePm.'"');
  1232. $resT = mysql_fetch_array($quert);
  1233. $neresult =$neresult+$resT[0];
  1234. echo $resT[0] . ",";
  1235. foreach ($col3 as $key => $value) {
  1236. $quer = mysql_query('select count(*) as total from lead where ws_agentId = "'.@$value[0].'" and updatedOn >= "'.@$time.'" and updatedOn <= "'.@$timePm.'"');
  1237. $res = mysql_fetch_array($quer);
  1238. $quer1 = mysql_query('select count(*) as total from lead where ws_agentId = "'.@$value[1].'" and updatedOn >= "'.@$time.'" and updatedOn <= "'.@$timePm.'"');
  1239. $res1 = mysql_fetch_array($quer1);
  1240. echo $res[0] . ",";
  1241. echo $res1[0] . ",";
  1242. // echo date('d:m:y::h:i:s A',$time) . ",";
  1243. $f++;
  1244. }
  1245. echo "\n";
  1246. }
  1247. echo 'total data'. ",";
  1248. echo $neresult. ",";
  1249. echo "\n";
  1250. }
  1251. }
  1252. public function actiondatamis_old(){
  1253. ini_set('max_input_time', 1200);
  1254. ini_set('max_execution_time', 1200);
  1255. $host = '10.216.6.59'; // MYSQL database host adress
  1256. $db = 'lms'; // MYSQL database name
  1257. $user = 'root'; // Mysql Datbase user
  1258. $pass = '0kwp6aNR'; // Mysql Datbase password
  1259. $link=mysql_connect($host,$user,$pass);
  1260. mysql_select_db($db,$link);
  1261. $table='report_datamis';
  1262. $chktableExist = mysql_query('DROP TABLE IF EXISTS '.$table.' ') or die(mysql_error());
  1263. $parser = new CHtmlPurifier();
  1264. $afterMonth = $parser->purify(intval(@$_REQUEST['month']));
  1265. $afterYear = $parser->purify(intval(@$_REQUEST['year']));
  1266. if(isset($afterMonth) && !empty($afterMonth) && isset($afterYear) && !empty($afterYear)){
  1267. $start =mktime(0, 0, 0, $afterMonth, 1,$afterYear);
  1268. $end = mktime(23, 59, 0, $afterMonth, date('t', $start),$afterYear);
  1269. } else {
  1270. $start = strtotime('first day of this month', time());
  1271. $end = strtotime('last day of this month', time());
  1272. }
  1273. mysql_query("UPDATE `leadSourceMaster` SET leadSourceTitleReport=REPLACE(leadSourceTitle,' ','_')");
  1274. mysql_query("UPDATE `leadSourceMaster` SET leadSourceTitleReport=REPLACE(leadSourceTitleReport,'-','_')");
  1275. mysql_query("SELECT
  1276. CONCAT('CREATE TABLE ".$table." (',
  1277. GROUP_CONCAT(DISTINCT CONCAT(leadSourceTitleReport, ' VARCHAR(50)') SEPARATOR ','),
  1278. ');')
  1279. FROM
  1280. leadSourceMaster
  1281. INTO @sql") or die(mysql_error());
  1282. mysql_query("PREPARE stmt FROM @sql");
  1283. mysql_query("EXECUTE stmt");
  1284. mysql_query("ALTER TABLE ".$table." ADD `AgentName` VARCHAR( 150 ) NOT NULL FIRST ,
  1285. ADD `Total` VARCHAR( 50 ) NOT NULL AFTER `AgentName`");
  1286. $sourcecode = mysql_query("select distinct leadSourceTitleReport as leadSourceTitle,leadsourceCode from leadSourceMaster group by leadSourceTitleReport");
  1287. $row=0;
  1288. $arraymerger = array();
  1289. // $start = strtotime('first day of this month', time());
  1290. //$end = strtotime('last day of this month', time());
  1291. $totalsourcewise = array();
  1292. $totalsourcewisesales = array();
  1293. $totalcontactable = array();
  1294. $conversionpercentage = array();
  1295. $salesIds = '36';
  1296. $contactableids = '7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22';
  1297. $noncontactableids = '27,28,42,43';
  1298. while ($row = mysql_fetch_array($sourcecode)){
  1299. //echo $row['leadsourceCode'];
  1300. $arraymerger[$row['leadsourceCode']] = $row['leadSourceTitle'] ;
  1301. //echo 'select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" THEN 1 ELSE 0 END) AS total from lead'; die;
  1302. $quersum = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" and updatedOn >= "'.@$start.'" and updatedOn <= "'.@$end.'" THEN 1 ELSE 0 END) AS total from lead');
  1303. $querressum = mysql_fetch_assoc($quersum);
  1304. $totalsourcewise[] = $querressum['total'];
  1305. $quersumsales = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" and updatedOn >= "'.@$start.'" and updatedOn <= "'.@$end.'" and leadStatusId IN('.@$salesIds.') THEN 1 ELSE 0 END) AS total from lead');
  1306. $querressumsales = mysql_fetch_assoc($quersumsales);
  1307. $totalsourcewisesales[] = $querressumsales['total'];
  1308. $conversionpercentage[$querressumsales['total']] = $querressum['total'];
  1309. $quersumcontactable = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" and updatedOn >= "'.@$start.'" and updatedOn <= "'.@$end.'" and leadStatusId IN('.@$contactableids.') THEN 1 ELSE 0 END) AS total from lead');
  1310. $querressumcontactable = mysql_fetch_assoc($quersumcontactable);
  1311. $totalcontactable[] = $querressumcontactable['total'];
  1312. $row++; }
  1313. $keys = (implode(",",array_keys($arraymerger)));
  1314. $values = (implode(",",array_values($arraymerger)));
  1315. $q="replace into ".$table." (AgentName,".$values.") values ('AgentCode',".$keys.")";
  1316. mysql_query($q) or die(mysql_error());
  1317. $maxDays=date('t');
  1318. $totalData = 0;
  1319. $totalDatasales = 0;
  1320. $totalDatacontactable = 0;
  1321. for($y=1;$y<=$maxDays;$y++) {
  1322. $date = $y.date('/m/Y');
  1323. $explodedDate = explode('/',$date);
  1324. $time = strtotime($explodedDate[0]."-".$explodedDate[1]."-".$explodedDate[2]);
  1325. $timePm = strtotime($explodedDate[0]."-".$explodedDate[1]."-".$explodedDate[2])+86399;
  1326. $totalcountcode = array();
  1327. $totalcountsales = array();
  1328. $totalcountcontact = array();
  1329. $totalcountcoderes=0;
  1330. foreach($arraymerger as $key=>$values1){
  1331. $quer = mysql_query('select count(*) as total from lead where ws_agentId = "'.@$key.'" and updatedOn >= "'.@$time.'" and updatedOn <= "'.@$timePm.'"');
  1332. $querres = mysql_fetch_assoc($quer);
  1333. $totalcountcode[] = $querres['total'];
  1334. $totalcountcoderes =$querres['total'];
  1335. $salesquery = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$key.'" and updatedOn >= "'.@$time.'" and updatedOn <= "'.@$timePm.'" and leadStatusId IN('.@$salesIds.') THEN 1 ELSE 0 END) as total from lead ');
  1336. $salesqueryres = mysql_fetch_array($salesquery);
  1337. $totalcountsales[] = $salesqueryres['total'];
  1338. $contactquery = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$key.'" and updatedOn >= "'.@$time.'" and updatedOn <= "'.@$timePm.'" and leadStatusId IN('.@$contactableids.') THEN 1 ELSE 0 END) as total from lead ');
  1339. $contactqueryres = mysql_fetch_array($contactquery);
  1340. $totalcountcontact[] = $contactqueryres['total'];
  1341. }
  1342. $totalsumres = array_sum($totalcountcode);
  1343. $totalsumresales = array_sum($totalcountsales);
  1344. $totalcountcontact = array_sum($totalcountcontact);
  1345. $implodedcountcode = implode(",",$totalcountcode);
  1346. $totalData = $totalData+intval($totalsumres);
  1347. $totalDatasales = $totalDatasales+intval($totalsumresales);
  1348. $totalDatacontactable = $totalDatacontactable+intval($totalcountcontact);
  1349. intval($totalcountcoderes);
  1350. $totalsumsales = array_sum($totalcountsales);
  1351. //print_r($totalcountsales);
  1352. $datequery = "insert into ".$table."(`AgentName`,`Total`,".$values.") values('".$y.date('/M/Y')."',".$totalsumres.",".$implodedcountcode.")";
  1353. mysql_query($datequery);
  1354. }
  1355. $contactper = $totalcontactable;
  1356. $datacontper = $totalsourcewise;
  1357. $datacontpertest = $totalsourcewisesales;
  1358. $totalsourcewise = implode(",",$totalsourcewise);
  1359. $totalsourcewisesales = implode(",",$totalsourcewisesales);
  1360. $totalcontactable = implode(",",$totalcontactable);
  1361. if(@$totalDatacontactable > 0){
  1362. $contactperc = '100';
  1363. } else {
  1364. $contactperc = '0';
  1365. }
  1366. $contactpervalu =array();
  1367. foreach($contactper as $key2=>$value2){
  1368. if($totalDatacontactable > 0){
  1369. $contactpervalu[] = '"'.($value2*100)/$totalDatacontactable.'%"';
  1370. } else {
  1371. $contactpervalu[] = "'0%'";
  1372. }
  1373. // $contactpervalu[] = '"'.($value2*100)/$totalDatacontactable.'%"';
  1374. }
  1375. $contactpervalu = implode(",",$contactpervalu);
  1376. if(@$totalData > 0){
  1377. $Datacontributionprec = '100';
  1378. } else {
  1379. $Datacontributionprec = '0';
  1380. }
  1381. $datacontpervalu =array();
  1382. foreach($datacontper as $key4=>$value4){
  1383. if($totalData > 0){
  1384. $datacontpervalu[] = '"'.($value4*100)/$totalData.'%"';
  1385. } else {
  1386. $datacontpervalu[] = "'0%'";
  1387. }
  1388. }
  1389. $datacontpervalu = implode(",",$datacontpervalu);
  1390. $conversionPerkeys = array_keys($conversionpercentage);
  1391. $conversionPervalue = array_values($conversionpercentage);
  1392. $conversionnetres = array();
  1393. for($r=0;$r<count($datacontper);$r++){
  1394. if($datacontper[$r] > 0){
  1395. $conversionnetres[$r] = ($datacontpertest[$r]/$datacontper[$r]);
  1396. } else {
  1397. $conversionnetres[$r] = "'0%'";;
  1398. }
  1399. }
  1400. $conversionpercentagevalu = implode(",",$conversionnetres);
  1401. if($totalData > 0){
  1402. $dataconversionrationtotal = ($totalDatasales/$totalData);
  1403. } else {
  1404. $dataconversionrationtotal = 0;
  1405. }
  1406. //echo "insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conatctable%','".@$contactperc."%',".@$contactpervalu.")"; die;
  1407. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('TotalData','".@$totalData."',".@$totalsourcewise.")");
  1408. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Sale','".@$totalDatasales."',".@$totalsourcewisesales.")");
  1409. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conatctabledata','".@$totalDatacontactable."',".@$totalcontactable.")");
  1410. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conatctable%','".@$contactperc."%',".@$contactpervalu.")");
  1411. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Datacontribution%','".@$Datacontributionprec."%',".@$datacontpervalu.")");
  1412. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conversion%','".@$dataconversionrationtotal."%',".@$conversionpercentagevalu.")");
  1413. // $tableres ="create table IF NOT EXISTS ".$table." as select leadSourceCode,leadSourceTitle from leadSourceMaster";
  1414. //$esx = mysql_query($tableres) or die(mysql_error());
  1415. $this->actiondatamis_download($start);
  1416. }
  1417. public function actiondatamis(){
  1418. ini_set('max_input_time', 19200);
  1419. ini_set('max_execution_time', 19200);
  1420. $host = '10.216.6.59'; // MYSQL database host adress
  1421. $db = 'lms'; // MYSQL database name
  1422. $user = 'root'; // Mysql Datbase user
  1423. $pass = '0kwp6aNR'; // Mysql Datbase password
  1424. $link=mysql_connect($host,$user,$pass);
  1425. mysql_select_db($db,$link);
  1426. $table='report_datamis';
  1427. $chktableExist = mysql_query('DROP TABLE IF EXISTS '.$table.' ') or die(mysql_error());
  1428. $parser = new CHtmlPurifier();
  1429. $afterMonth = $parser->purify(intval(@$_REQUEST['month']));
  1430. $afterYear = $parser->purify(intval(@$_REQUEST['year']));
  1431. if(isset($afterMonth) && !empty($afterMonth) && isset($afterYear) && !empty($afterYear)){
  1432. $start =mktime(0, 0, 0, $afterMonth, 1,$afterYear);
  1433. $end = mktime(23, 59, 0, $afterMonth, date('t', $start),$afterYear);
  1434. } else {
  1435. $start = strtotime('first day of this month', time());
  1436. $end = strtotime('last day of this month', time());
  1437. }
  1438. mysql_query("UPDATE `leadSourceMaster` SET leadSourceTitleReport=REPLACE(REPLACE(REPLACE(leadSourceTitle,' ',''),'-','_'),'.','')");
  1439. $resnews = mysql_query("SELECT group_concat(CONCAT(`leadSourceTitleReport`)) as res FROM `leadSourceMaster`");
  1440. $netres = mysql_fetch_array($resnews);
  1441. $strg = $netres['res'];
  1442. $replacedstr = str_replace(',',' varchar(50) ,',$strg)." varchar(50)";
  1443. $createsql = "CREATE TABLE IF NOT EXISTS ".$table." (
  1444. ".$replacedstr."
  1445. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
  1446. ";
  1447. mysql_query($createsql) or die(mysql_error());
  1448. mysql_query("ALTER TABLE ".$table." ADD `AgentName` VARCHAR( 150 ) NOT NULL FIRST ,
  1449. ADD `Total` VARCHAR( 50 ) NOT NULL AFTER `AgentName`");
  1450. $sourcecode = mysql_query("select distinct leadSourceTitleReport as leadSourceTitle,leadsourceCode from leadSourceMaster group by leadSourceTitleReport");
  1451. $row=0;
  1452. $arraymerger = array();
  1453. // $start = strtotime('first day of this month', time());
  1454. // $end = strtotime('last day of this month', time());
  1455. $totalsourcewise = array();
  1456. $totalsourcewisesales = array();
  1457. $totalcontactable = array();
  1458. $conversionpercentage = array();
  1459. $salesIds = '7';
  1460. $contactableids = '7,8,9,37,38,11,12,13,14,15,16,17,22,23,24,25,26';
  1461. $noncontactableids = '39,40,27,28,29,30,33,42,43';
  1462. while ($row = mysql_fetch_array($sourcecode)){
  1463. //echo $row['leadsourceCode'];
  1464. $arraymerger[$row['leadsourceCode']] = $row['leadSourceTitle'] ;
  1465. //echo 'select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" THEN 1 ELSE 0 END) AS total from lead'; die;
  1466. $quersum = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" and createdOn >= "'.@$start.'" and createdOn <= "'.@$end.'" AND leadStatusId !=36 AND leadStatusId !=10 THEN 1 ELSE 0 END) AS total from lead');
  1467. $querressum = mysql_fetch_assoc($quersum);
  1468. $totalsourcewise[] = $querressum['total'];
  1469. $quersumsales = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" and createdOn >= "'.@$start.'" and createdOn <= "'.@$end.'" AND leadStatusId !=36 AND leadStatusId !=10 and leadStatusId IN('.@$salesIds.') THEN 1 ELSE 0 END) AS total from lead');
  1470. $querressumsales = mysql_fetch_assoc($quersumsales);
  1471. $totalsourcewisesales[] = $querressumsales['total'];
  1472. $conversionpercentage[$querressumsales['total']] = $querressum['total'];
  1473. $quersumcontactable = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" and createdOn >= "'.@$start.'" and createdOn <= "'.@$end.'" AND leadStatusId !=36 AND leadStatusId !=10 and leadStatusId IN('.@$contactableids.') THEN 1 ELSE 0 END) AS total from lead');
  1474. $querressumcontactable = mysql_fetch_assoc($quersumcontactable);
  1475. $totalcontactable[] = $querressumcontactable['total'];
  1476. $row++; }
  1477. $keys = (implode(",",array_keys($arraymerger)));
  1478. $values = (implode(",",array_values($arraymerger)));
  1479. $q="replace into ".$table." (AgentName,".$values.") values ('AgentCode',".$keys.")";
  1480. mysql_query($q) or die(mysql_error());
  1481. // $maxDays=date('t');
  1482. $maxDays=date('d');
  1483. $totalData = 0;
  1484. $totalDatasales = 0;
  1485. $totalDatacontactable = 0;
  1486. for($y=1;$y<=$maxDays;$y++) {
  1487. $date = $y.date('/m/Y');
  1488. $explodedDate = explode('/',$date);
  1489. $time = strtotime($explodedDate[0]."-".$explodedDate[1]."-".$explodedDate[2]);
  1490. $timePm = strtotime($explodedDate[0]."-".$explodedDate[1]."-".$explodedDate[2])+86399;
  1491. $totalcountcode = array();
  1492. $totalcountsales = array();
  1493. $totalcountcontact = array();
  1494. $totalcountcoderes=0;
  1495. foreach($arraymerger as $key=>$values1){
  1496. $quer = mysql_query('select count(*) as total from lead where ws_agentId = "'.@$key.'" and createdOn >= "'.@$time.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$timePm.'"');
  1497. $querres = mysql_fetch_assoc($quer);
  1498. $totalcountcode[] = $querres['total'];
  1499. $totalcountcoderes =$querres['total'];
  1500. $salesquery = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$key.'" and createdOn >= "'.@$time.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$timePm.'" and leadStatusId IN('.@$salesIds.') THEN 1 ELSE 0 END) as total from lead ');
  1501. $salesqueryres = mysql_fetch_array($salesquery);
  1502. $totalcountsales[] = $salesqueryres['total'];
  1503. $contactquery = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$key.'" and createdOn >= "'.@$time.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$timePm.'" and leadStatusId IN('.@$contactableids.') THEN 1 ELSE 0 END) as total from lead ');
  1504. $contactqueryres = mysql_fetch_array($contactquery);
  1505. $totalcountcontact[] = $contactqueryres['total'];
  1506. }
  1507. $totalsumres = array_sum($totalcountcode);
  1508. $totalsumresales = array_sum($totalcountsales);
  1509. $totalcountcontact = array_sum($totalcountcontact);
  1510. $implodedcountcode = implode(",",$totalcountcode);
  1511. $totalData = $totalData+intval($totalsumres);
  1512. $totalDatasales = $totalDatasales+intval($totalsumresales);
  1513. $totalDatacontactable = $totalDatacontactable+intval($totalcountcontact);
  1514. intval($totalcountcoderes);
  1515. $totalsumsales = array_sum($totalcountsales);
  1516. //print_r($totalcountsales);
  1517. $datequery = "insert into ".$table."(`AgentName`,`Total`,".$values.") values('".$y.date('/M/Y')."',".$totalsumres.",".$implodedcountcode.")";
  1518. mysql_query($datequery);
  1519. }
  1520. $contactper = $totalcontactable;
  1521. $datacontper = $totalsourcewise;
  1522. $datacontpertest = $totalsourcewisesales;
  1523. $totalsourcewise = implode(",",$totalsourcewise);
  1524. $totalsourcewisesales = implode(",",$totalsourcewisesales);
  1525. $totalcontactable = implode(",",$totalcontactable);
  1526. if(@$totalDatacontactable > 0){
  1527. //$contactperc = ($totalDatacontactable*100)/$totalData;
  1528. $contactperc = ($totalDatasales*100)/$totalData;
  1529. } else {
  1530. $contactperc = '0';
  1531. }
  1532. $contactpervalu =array();
  1533. foreach($contactper as $key2=>$value2){
  1534. if($datacontper[$key2] > 0){
  1535. $contactpervalu[] = '"'.($value2*100)/$datacontper[$key2].'%"';
  1536. } else {
  1537. $contactpervalu[] = "'0%'";
  1538. }
  1539. // $contactpervalu[] = '"'.($value2*100)/$totalDatacontactable.'%"';
  1540. }
  1541. $contactpervalu = implode(",",$contactpervalu);
  1542. if(@$totalData > 0){
  1543. $Datacontributionprec = '100';
  1544. } else {
  1545. $Datacontributionprec = '0';
  1546. }
  1547. $datacontpervalu =array();
  1548. foreach($datacontper as $key4=>$value4){
  1549. if($totalData > 0){
  1550. $datacontpervalu[] = '"'.($value4*100)/$totalData.'%"';
  1551. } else {
  1552. $datacontpervalu[] = "'0%'";
  1553. }
  1554. }
  1555. $datacontpervalu = implode(",",$datacontpervalu);
  1556. $conversionPerkeys = array_keys($conversionpercentage);
  1557. $conversionPervalue = array_values($conversionpercentage);
  1558. $conversionnetres = array();
  1559. for($r=0;$r<count($datacontper);$r++){
  1560. if($datacontper[$r] > 0){
  1561. $conversionnetres[$r] = ($datacontpertest[$r]/$datacontper[$r]).'%"';
  1562. } else {
  1563. $conversionnetres[$r] = "'0%'";
  1564. }
  1565. }
  1566. $conversionpercentagevalu = implode(",",$conversionnetres);
  1567. if($totalData > 0){
  1568. $dataconversionrationtotal = ($totalDatasales/$totalData);
  1569. } else {
  1570. $dataconversionrationtotal = 0;
  1571. }
  1572. //echo "insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conatctable%','".@$contactperc."%',".@$contactpervalu.")"; die;
  1573. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('TotalData','".@$totalData."',".@$totalsourcewise.")");
  1574. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Sale','".@$totalDatasales."',".@$totalsourcewisesales.")");
  1575. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conatctabledata','".@$totalDatacontactable."',".@$totalcontactable.")");
  1576. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conatctable%','".@$contactperc."%',".@$contactpervalu.")");
  1577. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Datacontribution%','".@$Datacontributionprec."%',".@$datacontpervalu.")");
  1578. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conversion%','".@$dataconversionrationtotal."%',".@$conversionpercentagevalu.")");
  1579. // $tableres ="create table IF NOT EXISTS ".$table." as select leadSourceCode,leadSourceTitle from leadSourceMaster";
  1580. //$esx = mysql_query($tableres) or die(mysql_error());
  1581. $this->actiondatamis_download($start);
  1582. }
  1583. public function actiondatamis_download($start){
  1584. ini_set('max_input_time', 300);
  1585. ini_set('max_execution_time', 300);
  1586. $date = date('d_M_Y').'_';
  1587. $host = '10.216.6.59'; // MYSQL database host adress
  1588. $db = 'lms'; // MYSQL database name
  1589. $user = 'root'; // Mysql Datbase user
  1590. $pass = '0kwp6aNR'; // Mysql Datbase password
  1591. $link=mysql_connect($host,$user,$pass);
  1592. mysql_select_db($db,$link);
  1593. $table='report_datamis';
  1594. $filename = "filesystem/".$date.$table.'.csv';
  1595. $csv_terminated = "\n";
  1596. $csv_separator = ",";
  1597. $csv_enclosed = '"';
  1598. $csv_escaped = "\\";
  1599. $time = time();
  1600. mysql_query("insert into report_info (id,type,filename,createdOn,createdBy,updatedOn,updatedBy) values('','datadumpmis','".@$filename."','".@$time."','0','".@$time."','0')");
  1601. $sql_query = "select * from ".$table."";
  1602. // Gets the data from the database
  1603. $result = mysql_query($sql_query);
  1604. $fields_cnt = mysql_num_fields($result);
  1605. $schema_insert = '';
  1606. for ($i = 0; $i < $fields_cnt; $i++)
  1607. {
  1608. $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
  1609. stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
  1610. $schema_insert .= $l;
  1611. $schema_insert .= $csv_separator;
  1612. } // end for
  1613. $out = trim(substr($schema_insert, 0, -1));
  1614. $out .= $csv_terminated;
  1615. // Format the data
  1616. while ($row = mysql_fetch_array($result))
  1617. {
  1618. $schema_insert = '';
  1619. for ($j = 0; $j < $fields_cnt; $j++)
  1620. {
  1621. if ($row[$j] == '0' || $row[$j] != '')
  1622. {
  1623. if ($csv_enclosed == '')
  1624. {
  1625. $schema_insert .= $row[$j];
  1626. } else
  1627. {
  1628. $schema_insert .= $csv_enclosed .
  1629. str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
  1630. }
  1631. } else
  1632. {
  1633. $schema_insert .= '';
  1634. }
  1635. if ($j < $fields_cnt - 1)
  1636. {
  1637. $schema_insert .= $csv_separator;
  1638. }
  1639. } // end for
  1640. $out .= $schema_insert;
  1641. $out .= $csv_terminated;
  1642. } // end while
  1643. $fd = fopen($filename, "w");
  1644. fputs($fd, $out);
  1645. fclose($fd);
  1646. echo "success";
  1647. //header("Content-type: text/csv");
  1648. //header("Content-type: application/csv");
  1649. //echo $out;
  1650. exit;
  1651. }
  1652. public function actiondownloadallreports(){
  1653. $this->render('downloadallreports');
  1654. }
  1655. public function actiondatamisdatewise(){
  1656. ini_set('max_input_time', 19200);
  1657. ini_set('max_execution_time', 19200);
  1658. $host = '10.216.6.59'; // MYSQL database host adress
  1659. $db = 'lms'; // MYSQL database name
  1660. $user = 'root'; // Mysql Datbase user
  1661. $pass = '0kwp6aNR'; // Mysql Datbase password
  1662. $link=mysql_connect($host,$user,$pass);
  1663. mysql_select_db($db,$link);
  1664. $table='report_datamis';
  1665. $parser = new CHtmlPurifier();
  1666. $afterMonth = $parser->purify(intval(@$_REQUEST['month']));
  1667. $afterYear = $parser->purify(intval(@$_REQUEST['year']));
  1668. $afterDate = $parser->purify(intval(@$_REQUEST['date']));
  1669. $createTable = $parser->purify(intval(@$_REQUEST['create']));
  1670. if(isset($afterMonth) && !empty($afterMonth) && isset($afterYear) && !empty($afterYear) && isset($afterDate) && !empty($afterDate)){
  1671. $start =mktime(0, 0, 0, $afterMonth, 1,$afterYear);
  1672. $end = mktime(23, 59, 0, $afterMonth, date('t', $start),$afterYear);
  1673. } else {
  1674. $start = strtotime('first day of this month', time());
  1675. $end = strtotime('last day of this month', time());
  1676. }
  1677. if(isset($createTable) && !empty($createTable) && @$createTable==2){
  1678. $chktableExist = mysql_query('DROP TABLE IF EXISTS '.$table.' ') or die(mysql_error());
  1679. mysql_query("UPDATE `leadSourceMaster` SET leadSourceTitleReport=REPLACE(REPLACE(REPLACE(leadSourceTitle,' ',''),'-','_'),'.','')");
  1680. $resnews = mysql_query("SELECT group_concat(CONCAT(`leadSourceTitleReport`)) as res FROM `leadSourceMaster`");
  1681. $netres = mysql_fetch_array($resnews);
  1682. $strg = $netres['res'];
  1683. $replacedstr = str_replace(',',' varchar(50) ,',$strg)." varchar(50)";
  1684. $createsql = "CREATE TABLE IF NOT EXISTS ".$table." (
  1685. ".$replacedstr."
  1686. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
  1687. ";
  1688. mysql_query($createsql) or die(mysql_error());
  1689. mysql_query("ALTER TABLE ".$table." ADD `AgentName` VARCHAR( 150 ) NOT NULL FIRST ,
  1690. ADD `Total` VARCHAR( 50 ) NOT NULL AFTER `AgentName`");
  1691. }
  1692. $sourcecode = mysql_query("select distinct leadSourceTitleReport as leadSourceTitle,leadsourceCode from leadSourceMaster group by leadSourceTitleReport");
  1693. $row=0;
  1694. $arraymerger = array();
  1695. // $start = strtotime('first day of this month', time());
  1696. //$end = strtotime('last day of this month', time());
  1697. $totalsourcewise = array();
  1698. $totalsourcewisesales = array();
  1699. $totalcontactable = array();
  1700. $conversionpercentage = array();
  1701. $salesIds = '7';
  1702. $contactableids = '7,8,9,37,38,11,12,13,14,15,16,17,22,23,24,25,26';
  1703. $noncontactableids = '39,40,27,28,29,30,33,42,43';
  1704. while ($row = mysql_fetch_array($sourcecode)){
  1705. //echo $row['leadsourceCode'];
  1706. $arraymerger[$row['leadsourceCode']] = $row['leadSourceTitle'] ;
  1707. //echo 'select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" THEN 1 ELSE 0 END) AS total from lead'; die;
  1708. $quersum = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" and createdOn >= "'.@$start.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$end.'" THEN 1 ELSE 0 END) AS total from lead');
  1709. $querressum = mysql_fetch_assoc($quersum);
  1710. $totalsourcewise[] = $querressum['total'];
  1711. $quersumsales = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" and createdOn >= "'.@$start.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$end.'" and leadStatusId IN('.@$salesIds.') THEN 1 ELSE 0 END) AS total from lead');
  1712. $querressumsales = mysql_fetch_assoc($quersumsales);
  1713. $totalsourcewisesales[] = $querressumsales['total'];
  1714. $conversionpercentage[$querressumsales['total']] = $querressum['total'];
  1715. $quersumcontactable = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" and createdOn >= "'.@$start.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$end.'" and leadStatusId IN('.@$contactableids.') THEN 1 ELSE 0 END) AS total from lead');
  1716. $querressumcontactable = mysql_fetch_assoc($quersumcontactable);
  1717. $totalcontactable[] = $querressumcontactable['total'];
  1718. $row++; }
  1719. $keys = (implode(",",array_keys($arraymerger)));
  1720. $values = (implode(",",array_values($arraymerger)));
  1721. if(isset($createTable) && !empty($createTable) && @$createTable==2){
  1722. $q="replace into ".$table." (AgentName,".$values.") values ('AgentCode',".$keys.")";
  1723. mysql_query($q) or die(mysql_error());
  1724. }
  1725. $maxDays=date('t');
  1726. $totalData = 0;
  1727. $totalDatasales = 0;
  1728. $totalDatacontactable = 0;
  1729. //for($y=1;$y<=$maxDays;$y++) {}
  1730. $y=@$afterDate;
  1731. $date = $y.date('/m/Y');
  1732. $explodedDate = explode('/',$date);
  1733. $time = strtotime($explodedDate[0]."-".$explodedDate[1]."-".$explodedDate[2]);
  1734. $timePm = strtotime($explodedDate[0]."-".$explodedDate[1]."-".$explodedDate[2])+86399;
  1735. $totalcountcode = array();
  1736. $totalcountsales = array();
  1737. $totalcountcontact = array();
  1738. $totalcountcoderes=0;
  1739. foreach($arraymerger as $key=>$values1){
  1740. $quer = mysql_query('select count(*) as total from lead where ws_agentId = "'.@$key.'" and createdOn >= "'.@$time.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$timePm.'" ');
  1741. $querres = mysql_fetch_assoc($quer);
  1742. $totalcountcode[] = $querres['total'];
  1743. $totalcountcoderes =$querres['total'];
  1744. $salesquery = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$key.'" and createdOn >= "'.@$time.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$timePm.'" and leadStatusId IN('.@$salesIds.') THEN 1 ELSE 0 END) as total from lead ');
  1745. $salesqueryres = mysql_fetch_array($salesquery);
  1746. $totalcountsales[] = $salesqueryres['total'];
  1747. $contactquery = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$key.'" and createdOn >= "'.@$time.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$timePm.'" and leadStatusId IN('.@$contactableids.') THEN 1 ELSE 0 END) as total from lead ');
  1748. $contactqueryres = mysql_fetch_array($contactquery);
  1749. $totalcountcontact[] = $contactqueryres['total'];
  1750. }
  1751. $totalsumres = array_sum($totalcountcode);
  1752. $totalsumresales = array_sum($totalcountsales);
  1753. $totalcountcontact = array_sum($totalcountcontact);
  1754. $implodedcountcode = implode(",",$totalcountcode);
  1755. $totalData = $totalData+intval($totalsumres);
  1756. $totalDatasales = $totalDatasales+intval($totalsumresales);
  1757. $totalDatacontactable = $totalDatacontactable+intval($totalcountcontact);
  1758. intval($totalcountcoderes);
  1759. $totalsumsales = array_sum($totalcountsales);
  1760. //print_r($totalcountsales);
  1761. $datequery = "insert into ".$table."(`AgentName`,`Total`,".$values.") values('".$y.date('/M/Y')."',".$totalsumres.",".$implodedcountcode.")";
  1762. mysql_query($datequery);
  1763. ////////////
  1764. $contactper = $totalcontactable;
  1765. $datacontper = $totalsourcewise;
  1766. $datacontpertest = $totalsourcewisesales;
  1767. $totalsourcewise = implode(",",$totalsourcewise);
  1768. $totalsourcewisesales = implode(",",$totalsourcewisesales);
  1769. $totalcontactable = implode(",",$totalcontactable);
  1770. if(@$totalDatacontactable > 0){
  1771. $contactperc = '100';
  1772. } else {
  1773. $contactperc = '0';
  1774. }
  1775. $contactpervalu =array();
  1776. foreach($contactper as $key2=>$value2){
  1777. if($totalDatacontactable > 0){
  1778. $contactpervalu[] = '"'.($value2*100)/$totalDatacontactable.'%"';
  1779. } else {
  1780. $contactpervalu[] = "'0%'";
  1781. }
  1782. // $contactpervalu[] = '"'.($value2*100)/$totalDatacontactable.'%"';
  1783. }
  1784. $contactpervalu = implode(",",$contactpervalu);
  1785. if(@$totalData > 0){
  1786. $Datacontributionprec = '100';
  1787. } else {
  1788. $Datacontributionprec = '0';
  1789. }
  1790. $datacontpervalu =array();
  1791. foreach($datacontper as $key4=>$value4){
  1792. if($totalData > 0){
  1793. $datacontpervalu[] = '"'.($value4*100)/$totalData.'%"';
  1794. } else {
  1795. $datacontpervalu[] = "'0%'";
  1796. }
  1797. }
  1798. $datacontpervalu = implode(",",$datacontpervalu);
  1799. $conversionPerkeys = array_keys($conversionpercentage);
  1800. $conversionPervalue = array_values($conversionpercentage);
  1801. $conversionnetres = array();
  1802. for($r=0;$r<count($datacontper);$r++){
  1803. if($datacontper[$r] > 0){
  1804. $conversionnetres[$r] = ($datacontpertest[$r]/$datacontper[$r]);
  1805. } else {
  1806. $conversionnetres[$r] = "'0%'";;
  1807. }
  1808. }
  1809. $conversionpercentagevalu = implode(",",$conversionnetres);
  1810. if($totalData > 0){
  1811. $dataconversionrationtotal = ($totalDatasales/$totalData);
  1812. } else {
  1813. $dataconversionrationtotal = 0;
  1814. }
  1815. }
  1816. public function actiondatamiscreatetable(){
  1817. ini_set('max_input_time', 19200);
  1818. ini_set('max_execution_time', 19200);
  1819. $host = '10.216.6.59'; // MYSQL database host adress
  1820. $db = 'lms'; // MYSQL database name
  1821. $user = 'root'; // Mysql Datbase user
  1822. $pass = '0kwp6aNR'; // Mysql Datbase password
  1823. $link=mysql_connect($host,$user,$pass);
  1824. mysql_select_db($db,$link);
  1825. $table='report_datamis';
  1826. $parser = new CHtmlPurifier();
  1827. $afterMonth = $parser->purify(intval(@$_REQUEST['month']));
  1828. $afterYear = $parser->purify(intval(@$_REQUEST['year']));
  1829. $afterDate = $parser->purify(intval(@$_REQUEST['date']));
  1830. $createTable = $parser->purify(intval(@$_REQUEST['create']));
  1831. if(isset($afterMonth) && !empty($afterMonth) && isset($afterYear) && !empty($afterYear) && isset($afterDate) && !empty($afterDate)){
  1832. $start =mktime(0, 0, 0, $afterMonth, 1,$afterYear);
  1833. $end = mktime(23, 59, 0, $afterMonth, date('t', $start),$afterYear);
  1834. } else {
  1835. $start = strtotime('first day of this month', time());
  1836. $end = strtotime('last day of this month', time());
  1837. }
  1838. $chktableExist = mysql_query('DROP TABLE IF EXISTS '.$table.' ') or die(mysql_error());
  1839. mysql_query("UPDATE `leadSourceMaster` SET leadSourceTitleReport=REPLACE(REPLACE(REPLACE(leadSourceTitle,' ',''),'-','_'),'.','')");
  1840. $resnews = mysql_query("SELECT group_concat(CONCAT(`leadSourceTitleReport`)) as res FROM `leadSourceMaster`");
  1841. $netres = mysql_fetch_array($resnews);
  1842. $strg = $netres['res'];
  1843. $replacedstr = str_replace(',',' varchar(50) ,',$strg)." varchar(50)";
  1844. $createsql = "CREATE TABLE IF NOT EXISTS ".$table." (
  1845. ".$replacedstr."
  1846. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
  1847. ";
  1848. mysql_query($createsql) or die(mysql_error());
  1849. mysql_query("ALTER TABLE ".$table." ADD `AgentName` VARCHAR( 150 ) NOT NULL FIRST ,
  1850. ADD `Total` VARCHAR( 50 ) NOT NULL AFTER `AgentName`");
  1851. $sourcecode = mysql_query("select distinct leadSourceTitleReport as leadSourceTitle,leadsourceCode from leadSourceMaster group by leadSourceTitleReport");
  1852. $row=0;
  1853. $arraymerger = array();
  1854. // $start = strtotime('first day of this month', time());
  1855. //$end = strtotime('last day of this month', time());
  1856. $totalsourcewise = array();
  1857. $totalsourcewisesales = array();
  1858. $totalcontactable = array();
  1859. $conversionpercentage = array();
  1860. $salesIds = '7';
  1861. $contactableids = '7,8,9,37,38,11,12,13,14,15,16,17,22,23,24,25,26';
  1862. $noncontactableids = '39,40,27,28,29,30,33,42,43';
  1863. while ($row = mysql_fetch_array($sourcecode)){
  1864. //echo $row['leadsourceCode'];
  1865. $arraymerger[$row['leadsourceCode']] = $row['leadSourceTitle'] ;
  1866. //echo 'select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" THEN 1 ELSE 0 END) AS total from lead'; die;
  1867. $quersum = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" and createdOn >= "'.@$start.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$end.'" THEN 1 ELSE 0 END) AS total from lead');
  1868. $querressum = mysql_fetch_assoc($quersum);
  1869. $totalsourcewise[] = $querressum['total'];
  1870. $quersumsales = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" and createdOn >= "'.@$start.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$end.'" and leadStatusId IN('.@$salesIds.') THEN 1 ELSE 0 END) AS total from lead');
  1871. $querressumsales = mysql_fetch_assoc($quersumsales);
  1872. $totalsourcewisesales[] = $querressumsales['total'];
  1873. $conversionpercentage[$querressumsales['total']] = $querressum['total'];
  1874. $quersumcontactable = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" and createdOn >= "'.@$start.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$end.'" and leadStatusId IN('.@$contactableids.') THEN 1 ELSE 0 END) AS total from lead');
  1875. $querressumcontactable = mysql_fetch_assoc($quersumcontactable);
  1876. $totalcontactable[] = $querressumcontactable['total'];
  1877. $row++; }
  1878. $keys = (implode(",",array_keys($arraymerger)));
  1879. $values = (implode(",",array_values($arraymerger)));
  1880. $q="replace into ".$table." (AgentName,".$values.") values ('AgentCode',".$keys.")";
  1881. mysql_query($q) or die(mysql_error());
  1882. die;
  1883. $maxDays=date('t');
  1884. $totalData = 0;
  1885. $totalDatasales = 0;
  1886. $totalDatacontactable = 0;
  1887. //for($y=1;$y<=$maxDays;$y++) {}
  1888. $y=@$afterDate;
  1889. $date = $y.date('/m/Y');
  1890. $explodedDate = explode('/',$date);
  1891. $time = strtotime($explodedDate[0]."-".$explodedDate[1]."-".$explodedDate[2]);
  1892. $timePm = strtotime($explodedDate[0]."-".$explodedDate[1]."-".$explodedDate[2])+86399;
  1893. $totalcountcode = array();
  1894. $totalcountsales = array();
  1895. $totalcountcontact = array();
  1896. $totalcountcoderes=0;
  1897. foreach($arraymerger as $key=>$values1){
  1898. $quer = mysql_query('select count(*) as total from lead where ws_agentId = "'.@$key.'" and createdOn >= "'.@$time.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$timePm.'"');
  1899. $querres = mysql_fetch_assoc($quer);
  1900. $totalcountcode[] = $querres['total'];
  1901. $totalcountcoderes =$querres['total'];
  1902. $salesquery = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$key.'" and createdOn >= "'.@$time.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$timePm.'" and leadStatusId IN('.@$salesIds.') THEN 1 ELSE 0 END) as total from lead ');
  1903. $salesqueryres = mysql_fetch_array($salesquery);
  1904. $totalcountsales[] = $salesqueryres['total'];
  1905. $contactquery = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$key.'" and createdOn >= "'.@$time.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$timePm.'" and leadStatusId IN('.@$contactableids.') THEN 1 ELSE 0 END) as total from lead ');
  1906. $contactqueryres = mysql_fetch_array($contactquery);
  1907. $totalcountcontact[] = $contactqueryres['total'];
  1908. }
  1909. $totalsumres = array_sum($totalcountcode);
  1910. $totalsumresales = array_sum($totalcountsales);
  1911. $totalcountcontact = array_sum($totalcountcontact);
  1912. $implodedcountcode = implode(",",$totalcountcode);
  1913. $totalData = $totalData+intval($totalsumres);
  1914. $totalDatasales = $totalDatasales+intval($totalsumresales);
  1915. $totalDatacontactable = $totalDatacontactable+intval($totalcountcontact);
  1916. intval($totalcountcoderes);
  1917. $totalsumsales = array_sum($totalcountsales);
  1918. //print_r($totalcountsales);
  1919. $datequery = "insert into ".$table."(`AgentName`,`Total`,".$values.") values('".$y.date('/M/Y')."',".$totalsumres.",".$implodedcountcode.")";
  1920. mysql_query($datequery);
  1921. ////////////
  1922. $contactper = $totalcontactable;
  1923. $datacontper = $totalsourcewise;
  1924. $datacontpertest = $totalsourcewisesales;
  1925. $totalsourcewise = implode(",",$totalsourcewise);
  1926. $totalsourcewisesales = implode(",",$totalsourcewisesales);
  1927. $totalcontactable = implode(",",$totalcontactable);
  1928. if(@$totalDatacontactable > 0){
  1929. $contactperc = '100';
  1930. } else {
  1931. $contactperc = '0';
  1932. }
  1933. $contactpervalu =array();
  1934. foreach($contactper as $key2=>$value2){
  1935. if($totalDatacontactable > 0){
  1936. $contactpervalu[] = '"'.($value2*100)/$totalDatacontactable.'%"';
  1937. } else {
  1938. $contactpervalu[] = "'0%'";
  1939. }
  1940. // $contactpervalu[] = '"'.($value2*100)/$totalDatacontactable.'%"';
  1941. }
  1942. $contactpervalu = implode(",",$contactpervalu);
  1943. if(@$totalData > 0){
  1944. $Datacontributionprec = '100';
  1945. } else {
  1946. $Datacontributionprec = '0';
  1947. }
  1948. $datacontpervalu =array();
  1949. foreach($datacontper as $key4=>$value4){
  1950. if($totalData > 0){
  1951. $datacontpervalu[] = '"'.($value4*100)/$totalData.'%"';
  1952. } else {
  1953. $datacontpervalu[] = "'0%'";
  1954. }
  1955. }
  1956. $datacontpervalu = implode(",",$datacontpervalu);
  1957. $conversionPerkeys = array_keys($conversionpercentage);
  1958. $conversionPervalue = array_values($conversionpercentage);
  1959. $conversionnetres = array();
  1960. for($r=0;$r<count($datacontper);$r++){
  1961. if($datacontper[$r] > 0){
  1962. $conversionnetres[$r] = ($datacontpertest[$r]/$datacontper[$r]);
  1963. } else {
  1964. $conversionnetres[$r] = "'0%'";;
  1965. }
  1966. }
  1967. $conversionpercentagevalu = implode(",",$conversionnetres);
  1968. if($totalData > 0){
  1969. $dataconversionrationtotal = ($totalDatasales/$totalData);
  1970. } else {
  1971. $dataconversionrationtotal = 0;
  1972. }
  1973. }
  1974. public function actiondatamistotaldata(){
  1975. ini_set('max_input_time', 19200);
  1976. ini_set('max_execution_time', 19200);
  1977. $host = '10.216.6.59'; // MYSQL database host adress
  1978. $db = 'lms'; // MYSQL database name
  1979. $user = 'root'; // Mysql Datbase user
  1980. $pass = '0kwp6aNR'; // Mysql Datbase password
  1981. $link=mysql_connect($host,$user,$pass);
  1982. mysql_select_db($db,$link);
  1983. $table='report_datamis';
  1984. $parser = new CHtmlPurifier();
  1985. $afterMonth = $parser->purify(intval(@$_REQUEST['month']));
  1986. $afterYear = $parser->purify(intval(@$_REQUEST['year']));
  1987. $afterDate = $parser->purify(intval(@$_REQUEST['date']));
  1988. if(isset($afterMonth) && !empty($afterMonth) && isset($afterYear) && !empty($afterYear)){
  1989. $start =mktime(0, 0, 0, $afterMonth, 1,$afterYear);
  1990. $end = mktime(23, 59, 0, $afterMonth, date('t', $start),$afterYear);
  1991. } else {
  1992. $start = strtotime('first day of this month', time());
  1993. $end = strtotime('last day of this month', time());
  1994. }
  1995. $sourcecode = mysql_query("select distinct leadSourceTitleReport as leadSourceTitle,leadsourceCode from leadSourceMaster group by leadSourceTitleReport");
  1996. $row=0;
  1997. $arraymerger = array();
  1998. // $start = strtotime('first day of this month', time());
  1999. //$end = strtotime('last day of this month', time());
  2000. $totalsourcewise = array();
  2001. $totalsourcewisesales = array();
  2002. $totalcontactable = array();
  2003. $conversionpercentage = array();
  2004. $salesIds = '7';
  2005. $contactableids = '7,8,9,37,38,11,12,13,14,15,16,17,22,23,24,25,26';
  2006. $noncontactableids = '39,40,27,28,29,30,33,42,43';
  2007. while ($row = mysql_fetch_array($sourcecode)){
  2008. //echo $row['leadsourceCode'];
  2009. $arraymerger[$row['leadsourceCode']] = $row['leadSourceTitle'] ;
  2010. //echo 'select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" THEN 1 ELSE 0 END) AS total from lead'; die;
  2011. $quersum = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" and createdOn >= "'.@$start.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$end.'" THEN 1 ELSE 0 END) AS total from lead');
  2012. $querressum = mysql_fetch_assoc($quersum);
  2013. $totalsourcewise[] = $querressum['total'];
  2014. $quersumsales = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" and createdOn >= "'.@$start.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$end.'" and leadStatusId IN('.@$salesIds.') THEN 1 ELSE 0 END) AS total from lead');
  2015. $querressumsales = mysql_fetch_assoc($quersumsales);
  2016. $totalsourcewisesales[] = $querressumsales['total'];
  2017. $conversionpercentage[$querressumsales['total']] = $querressum['total'];
  2018. $quersumcontactable = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" and createdOn >= "'.@$start.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$end.'" and leadStatusId IN('.@$contactableids.') THEN 1 ELSE 0 END) AS total from lead');
  2019. $querressumcontactable = mysql_fetch_assoc($quersumcontactable);
  2020. $totalcontactable[] = $querressumcontactable['total'];
  2021. $row++; }
  2022. $keys = (implode(",",array_keys($arraymerger)));
  2023. $values = (implode(",",array_values($arraymerger)));
  2024. $maxDays=@$afterDate;
  2025. $totalData = 0;
  2026. $totalDatasales = 0;
  2027. $totalDatacontactable = 0;
  2028. for($y=1;$y<=$maxDays;$y++) {
  2029. $date = $y.date('/m/Y');
  2030. $explodedDate = explode('/',$date);
  2031. $time = strtotime($explodedDate[0]."-".$explodedDate[1]."-".$explodedDate[2]);
  2032. $timePm = strtotime($explodedDate[0]."-".$explodedDate[1]."-".$explodedDate[2])+86399;
  2033. $totalcountcode = array();
  2034. $totalcountsales = array();
  2035. $totalcountcontact = array();
  2036. $totalcountcoderes=0;
  2037. foreach($arraymerger as $key=>$values1){
  2038. $quer = mysql_query('select count(*) as total from lead where ws_agentId = "'.@$key.'" and createdOn >= "'.@$time.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$timePm.'"');
  2039. $querres = mysql_fetch_assoc($quer);
  2040. $totalcountcode[] = $querres['total'];
  2041. $totalcountcoderes =$querres['total'];
  2042. $salesquery = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$key.'" and createdOn >= "'.@$time.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$timePm.'" and leadStatusId IN('.@$salesIds.') THEN 1 ELSE 0 END) as total from lead ');
  2043. $salesqueryres = mysql_fetch_array($salesquery);
  2044. $totalcountsales[] = $salesqueryres['total'];
  2045. $contactquery = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$key.'" and createdOn >= "'.@$time.'" AND leadStatusId !=36 AND leadStatusId !=10 and createdOn <= "'.@$timePm.'" and leadStatusId IN('.@$contactableids.') THEN 1 ELSE 0 END) as total from lead ');
  2046. $contactqueryres = mysql_fetch_array($contactquery);
  2047. $totalcountcontact[] = $contactqueryres['total'];
  2048. }
  2049. $totalsumres = array_sum($totalcountcode);
  2050. $totalsumresales = array_sum($totalcountsales);
  2051. $totalcountcontact = array_sum($totalcountcontact);
  2052. $implodedcountcode = implode(",",$totalcountcode);
  2053. $totalData = $totalData+intval($totalsumres);
  2054. $totalDatasales = $totalDatasales+intval($totalsumresales);
  2055. $totalDatacontactable = $totalDatacontactable+intval($totalcountcontact);
  2056. intval($totalcountcoderes);
  2057. $totalsumsales = array_sum($totalcountsales);
  2058. //print_r($totalcountsales);
  2059. //$datequery = "insert into ".$table."(`AgentName`,`Total`,".$values.") values('".$y.date('/M/Y')."',".$totalsumres.",".$implodedcountcode.")";
  2060. //mysql_query($datequery);
  2061. }
  2062. $contactper = $totalcontactable;
  2063. $datacontper = $totalsourcewise;
  2064. $datacontpertest = $totalsourcewisesales;
  2065. $totalsourcewise = implode(",",$totalsourcewise);
  2066. $totalsourcewisesales = implode(",",$totalsourcewisesales);
  2067. $totalcontactable = implode(",",$totalcontactable);
  2068. if(@$totalDatacontactable > 0){
  2069. $contactperc = ($totalDatasales*100)/$totalData;
  2070. } else {
  2071. $contactperc = '0';
  2072. }
  2073. $contactpervalu =array();
  2074. foreach($contactper as $key2=>$value2){
  2075. if($totalDatacontactable > 0){
  2076. $contactpervalu[] = '"'.($value2*100)/$totalDatacontactable.'%"';
  2077. } else {
  2078. $contactpervalu[] = "'0%'";
  2079. }
  2080. // $contactpervalu[] = '"'.($value2*100)/$totalDatacontactable.'%"';
  2081. }
  2082. $contactpervalu = implode(",",$contactpervalu);
  2083. if(@$totalData > 0){
  2084. $Datacontributionprec = '100';
  2085. } else {
  2086. $Datacontributionprec = '0';
  2087. }
  2088. $datacontpervalu =array();
  2089. foreach($datacontper as $key4=>$value4){
  2090. if($totalData > 0){
  2091. $datacontpervalu[] = '"'.($value4*100)/$totalData.'%"';
  2092. } else {
  2093. $datacontpervalu[] = "'0%'";
  2094. }
  2095. }
  2096. $datacontpervalu = implode(",",$datacontpervalu);
  2097. $conversionPerkeys = array_keys($conversionpercentage);
  2098. $conversionPervalue = array_values($conversionpercentage);
  2099. $conversionnetres = array();
  2100. for($r=0;$r<count($datacontper);$r++){
  2101. if($datacontper[$r] > 0){
  2102. $conversionnetres[$r] = ($datacontpertest[$r]/$datacontper[$r]);
  2103. } else {
  2104. $conversionnetres[$r] = "'0%'";;
  2105. }
  2106. }
  2107. $conversionpercentagevalu = implode(",",$conversionnetres);
  2108. if($totalData > 0){
  2109. $dataconversionrationtotal = ($totalDatasales/$totalData);
  2110. } else {
  2111. $dataconversionrationtotal = 0;
  2112. }
  2113. //echo "insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conatctable%','".@$contactperc."%',".@$contactpervalu.")"; die;
  2114. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('TotalData','".@$totalData."',".@$totalsourcewise.")");
  2115. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Sale','".@$totalDatasales."',".@$totalsourcewisesales.")");
  2116. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conatctabledata','".@$totalDatacontactable."',".@$totalcontactable.")");
  2117. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conatctable%','".@$contactperc."%',".@$contactpervalu.")");
  2118. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Datacontribution%','".@$Datacontributionprec."%',".@$datacontpervalu.")");
  2119. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conversion%','".@$dataconversionrationtotal."%',".@$conversionpercentagevalu.")");
  2120. // $tableres ="create table IF NOT EXISTS ".$table." as select leadSourceCode,leadSourceTitle from leadSourceMaster";
  2121. //$esx = mysql_query($tableres) or die(mysql_error());
  2122. }
  2123. public function actiondatamisdownloadreport(){
  2124. ini_set('max_input_time', 19200);
  2125. ini_set('max_execution_time', 19200);
  2126. $host = '10.216.6.59'; // MYSQL database host adress
  2127. $db = 'lms'; // MYSQL database name
  2128. $user = 'root'; // Mysql Datbase user
  2129. $pass = '0kwp6aNR'; // Mysql Datbase password
  2130. $link=mysql_connect($host,$user,$pass);
  2131. mysql_select_db($db,$link);
  2132. $table='report_datamis';
  2133. if(isset($afterMonth) && !empty($afterMonth) && isset($afterYear) && !empty($afterYear)){
  2134. $start =mktime(0, 0, 0, $afterMonth, 1,$afterYear);
  2135. $end = mktime(23, 59, 0, $afterMonth, date('t', $start),$afterYear);
  2136. } else {
  2137. $start = strtotime('first day of this month', time());
  2138. $end = strtotime('last day of this month', time());
  2139. }
  2140. $this->actiondatamis_download($start);}
  2141. }
  2142. ?>