PageRenderTime 64ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/lms_debug/protected/controllers/ReportsController.php

https://gitlab.com/badelal143/lms_debug
PHP | 1881 lines | 1515 code | 259 blank | 107 comment | 252 complexity | 99fef50f9b4be590022ce0de046ffd27 MD5 | raw file
Possible License(s): LGPL-2.1, LGPL-3.0, LGPL-2.0
  1. <?php
  2. class ReportsController 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. @$mobile=@$_POST['LeadCronReport']['mobile'];
  43. @$datetype=@$_POST['LeadCronReport']['datetype'];
  44. if(isset($datetype) && !empty($datetype)){
  45. $datetype=$datetype;
  46. } else {
  47. $datetype='updatedOn';
  48. }
  49. $isjunk = @$_REQUEST['isJunk'];
  50. $isjunk = $isjunk?$isjunk:'no';
  51. $this->actionCreateExcel($getName,$getStatus,$getStage,$date1,$date2,$getleadSourceId,$getleadStatusId,$datetype,$isjunk,$mobile);
  52. }
  53. /**
  54. * Action Report.
  55. */
  56. public function actionreports()
  57. {
  58. $model = new LeadCronReport('search');
  59. $model->scenario = 'LeadCronReport';
  60. $teamId = '';
  61. $teamUserId = '';
  62. if (@$_POST['LeadCronReport'] != '' && isset($_POST['LeadCronReport']))
  63. {
  64. if (Yii::app()->session->get('roleName') == 'agent')
  65. {
  66. @$_POST['LeadCronReport']['ws_agentid'] = self::getAgentId();
  67. }
  68. @$primaryLeadStatus = @$_POST['leadStatusId'];
  69. if (count($primaryLeadStatus) > 0)
  70. {
  71. $primaryLeadStatus = implode(",", $primaryLeadStatus);
  72. $primaryDisposition = Yii::app()->db->createCommand("select leadStatus.leadStatus,leadStatusId from leadStatus where parentId IN (" . @$primaryLeadStatus . ") ")->queryAll();
  73. if (count($primaryDisposition) > 0)
  74. {
  75. for ($w = 0; $w < count($primaryDisposition); $w++)
  76. {
  77. @$PrimaryDispositionIds[] = @$primaryDisposition[$w]['leadStatusId'];
  78. }
  79. }
  80. else
  81. {
  82. @$PrimaryDispositionIds[] = '';
  83. }
  84. @$PrimaryDispositionIds = implode(",", @$PrimaryDispositionIds);
  85. }
  86. else
  87. {
  88. @$PrimaryDispositionIds = '';
  89. }
  90. $teamId = @$_POST['Team']['teamId'];
  91. $teamUserId = @$_POST['Team']['teamMemberId'];
  92. if ($teamUserId == '' or empty($teamUserId))
  93. {
  94. $teamUsers = Yii::app()->db->createCommand("select userId from teamUserMapping where teamId = '" . @$teamId . "' ")->queryAll();
  95. $reportsteamUsersIds = array();
  96. foreach ($teamUsers as $key => $value)
  97. {
  98. $reportsteamUsersIds[] = $value['userId'];
  99. }
  100. }
  101. else
  102. {
  103. $reportsteamUsersIds[] = $teamUserId;
  104. }
  105. $name = @$_POST['LeadCronReport']['name'];
  106. $status = @$_POST['LeadCronReport']['status'];
  107. $stage = @$_POST['LeadCronReport']['stage'];
  108. /* $utmCode=@$_POST['LeadCronReport']['utmCode'];
  109. $teleCaller=@$_POST['LeadCronReport']['teleCaller']; */
  110. $period1 = @$_POST['LeadCronReport']['period1'];
  111. $period2 = @$_POST['LeadCronReport']['period2'];
  112. $leadSourceId = @$_POST['LeadCronReport']['leadSourceId'];
  113. $ws_agentid = @$_POST['LeadCronReport']['ws_agentid'];
  114. $datetype = @$_POST['LeadCronReport']['datetype'];
  115. $isjunk = @$_REQUEST['isJunk'];
  116. $mobile = @$_POST['LeadCronReport']['mobile'];
  117. $isjunk = $isjunk ? $isjunk : 'no';
  118. if (isset($datetype) && !empty($datetype))
  119. {
  120. $datetype = $datetype;
  121. }
  122. else
  123. {
  124. $datetype = 'updatedOn';
  125. }
  126. //echo $datetype; die;
  127. $criteria = new CDbCriteria;
  128. $criteria->select = 't.*,`city`.`city`,`state`.`state`, `leadSourceMaster`.`leadSourceTitle`, `leadStageMaster`.`leadStage`,`leadStatus`.`leadStatus`,`customerTypeMaster`.`customerType`,`productMaster`.`productName`,`policyTypeMaster`.`policyType`,`planTypeMaster`.`planType`,`campaign`.`campaignName`';
  129. $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)';
  130. $criteria->order = 'leadId DESC';
  131. if (count($reportsteamUsersIds) > 0)
  132. {
  133. $comd = implode(',', $reportsteamUsersIds);
  134. $criteria->addCondition("t.currentAllocatedId IN (" . $comd . ") ");
  135. }
  136. if (isset($name) && !empty($name))
  137. {/* LIKE '$this->time_up%'"; */
  138. $criteria->addCondition("t.name like '%" . $name . "%'");
  139. }
  140. if (isset($status) && !empty($status))
  141. {
  142. $criteria->addCondition("t.leadStatusId =" . $status);
  143. }
  144. if (isset($PrimaryDispositionIds) && !empty($PrimaryDispositionIds))
  145. {
  146. $criteria->addCondition("t.leadStatusId IN (" . @$PrimaryDispositionIds . ") ");
  147. }
  148. if (isset($stage) && !empty($stage))
  149. {
  150. $criteria->addCondition("t.leadStageId =" . $stage);
  151. }
  152. if (isset($leadSourceId) && !empty($leadSourceId))
  153. {
  154. $criteria->addCondition("t.leadSourceId =" . $leadSourceId);
  155. }
  156. if (isset($isjunk) && !empty($isjunk) && $isjunk == 'yes')
  157. {
  158. $criteria->addCondition("t.leadStatusId !=36");
  159. }
  160. if (isset($ws_agentid) && !empty($ws_agentid))
  161. {
  162. $criteria->addCondition("t.leadSourceId='" . $ws_agentid . "'");
  163. }
  164. if (isset($mobile) && !empty($mobile))
  165. {
  166. $criteria->addCondition("t.mobile='" . $mobile . "'");
  167. }
  168. if ((isset($period1) && !empty($period1)) && (isset($period2) && !empty($period2)))
  169. {
  170. $period1 = strtotime($period1);
  171. $period2 = strtotime($period2) + 86399;
  172. // echo date('d m y :: h: i: s: A',$period2); die;
  173. $criteria->addCondition('t.' . $datetype . ' >= ' . $period1 . ' AND t.' . $datetype . ' <= ' . $period2 . '');
  174. // $criteria->addBetweenCondition('t.'.$datetype,$period1,$period2,'');
  175. }
  176. $model->set_name = @$_POST['LeadCronReport']['name'];
  177. $model->set_stage = @$_POST['LeadCronReport']['stage'];
  178. $model->set_status = @$_POST['LeadCronReport']['status'];
  179. $model->set_period1 = @$_POST['LeadCronReport']['period1'];
  180. $model->set_period2 = @$_POST['LeadCronReport']['period2'];
  181. $model->set_leadStatusId = @$_POST['leadStatusId'];
  182. $model->set_leadSourceId = @$_POST['LeadCronReport']['leadSourceId'];
  183. $model->set_ws_agentid = @$_POST['LeadCronReport']['ws_agentid'];
  184. $model->set_mobile = @$_POST['LeadCronReport']['mobile'];
  185. $criteria->order = 'leadId DESC';
  186. $dataProvider = new CActiveDataProvider('LeadCronReport', array('criteria' => $criteria, 'pagination' => array(
  187. 'pageSize' => 20,
  188. 'params' => array('period1' => @$period1 ? date("d-m-Y", @$period1) : '', 'period2' => @$period2 ? date("d-m-Y", @$period2) : ''),
  189. ),));
  190. if (Yii::app()->session->get('roleName') == 'agent')
  191. {
  192. $this->render('agentreports', array('model' => $model, 'dataProvider' => $dataProvider));
  193. }
  194. else
  195. {
  196. $this->render('reports', array('model' => $model, 'dataProvider' => $dataProvider, 'teamId' => $teamId, 'teamUserId' => $teamUserId));
  197. }
  198. }
  199. else
  200. {
  201. $criteria = new CDbCriteria;
  202. $criteria->select = 't.*';
  203. $criteria->order = 'leadId DESC';
  204. if (Yii::app()->session->get('roleName') == 'agent')
  205. {
  206. $criteria->condition = 'leadSourceId = ' . self::getAgentId();
  207. $dataProvider = new CActiveDataProvider('LeadCronReport', array('criteria' => $criteria,));
  208. $this->render('agentreports', array('model' => $model, 'dataProvider' => $dataProvider, 'teamId' => $teamId, 'teamUserId' => $teamUserId));
  209. }
  210. else
  211. {
  212. $dataProvider = new CActiveDataProvider('LeadCronReport', array('criteria' => $criteria,));
  213. $this->render('reports', array('model' => $model, 'dataProvider' => $dataProvider, 'teamId' => $teamId, 'teamUserId' => $teamUserId));
  214. }
  215. }
  216. }
  217. /**
  218. * Get Agent Id.
  219. * @return int.
  220. */
  221. public static function getAgentId()
  222. {
  223. $userId = Yii::app()->session->get('id');
  224. //echo "select leadsourcecode from leadsourcemaster where leadsourceid = (select leadsourceid from user where id = $userId )"; die;
  225. $leadSourceId = Yii::app()->db->createCommand("select leadsourceid from user where id = $userId ")->queryRow();
  226. return $leadSourceId['leadsourceid'];
  227. }
  228. /**
  229. * This function is used to get column name from number of column
  230. * calls from 'actionCreateExcel' function.
  231. */
  232. public function getNameFromNumber($num) {
  233. $numeric = $num % 26;
  234. $letter = chr(65 + $numeric);
  235. $num2 = intval($num / 26);
  236. if ($num2 > 0) {
  237. return getNameFromNumber($num2 - 1) . $letter;
  238. } else {
  239. return $letter;
  240. }
  241. }
  242. public function getPageType()
  243. {
  244. return "Reports";
  245. }
  246. /**
  247. * This function is used to create excel file
  248. * calls from 'actionreports' function.
  249. */
  250. public function actionCreateExcel($getName,$getStatus,$getStage,$date1,$date2,$getleadSourceId,$getleadStatusId,$datetype,$isjunk,$mobile){
  251. $paginationExcelValue = @$_POST['fetchrecordsBydropdown'];
  252. if(isset($paginationExcelValue) && !empty($paginationExcelValue)){
  253. $explodedpaginationValue = explode('-',$paginationExcelValue);
  254. $startLimit = $explodedpaginationValue[0];
  255. $endLimit = 10000;
  256. } else {
  257. $startLimit = '';
  258. $endLimit = '';
  259. }
  260. if(isset($startLimit) && isset($endLimit) && !empty($endLimit)){
  261. $limitCond = " limit $startLimit , $endLimit";
  262. } else {
  263. $limitCond = '';
  264. }
  265. //Here is the code to set conditions for fetch records from database
  266. $condfilter = '';
  267. if((isset($getName)&& (!empty($getName))) || (isset($getStatus)&& (!empty($getStatus))) || (isset($getStage)&& (!empty($getStage)))|| (isset($date1)&& (!empty($date1))) || (isset($date2)&& (!empty($date2))))
  268. {
  269. if(isset($getName) && !empty($getName))
  270. {
  271. $condfilter .= "t.name like '%".$getName."' AND ";
  272. }
  273. if(isset($getStatus) && !empty($getStatus))
  274. {
  275. $condfilter .= "t.leadStatusId =".$getStatus." AND ";
  276. }
  277. if(isset($getStage) && !empty($getStage))
  278. {
  279. $condfilter .= "t.leadStageId =".$getStage." AND ";
  280. }
  281. if(isset($getleadSourceId) && !empty($getleadSourceId))
  282. {
  283. $condfilter .= "t.leadSourceId =".$getleadSourceId." AND ";
  284. }
  285. if(isset($isjunk) && !empty($isjunk) && $isjunk=='yes' )
  286. {
  287. $condfilter .= "t.leadStatusId != 36 AND ";
  288. }
  289. if(isset($mobile) && !empty($mobile))
  290. {
  291. $condfilter .= "t.mobile ='".$mobile."' AND ";
  292. }
  293. if((isset($date1) && !empty($date1)) && (isset($date2) && !empty($date2)))
  294. {
  295. $date1=strtotime($date1);
  296. $date2=strtotime($date2)+86399;
  297. $condfilter .= "t.".$datetype." >=".$date1." AND t.".$datetype." <= ".$date2." AND ";
  298. }
  299. if(isset($condfilter) && !empty($condfilter)){
  300. $wherecon = "WHERE ";
  301. } else {
  302. $wherecon = "";
  303. }
  304. $data=Yii::app()->db->createCommand("select t.leadId,t.name,t.mobile,t.email,t.address,t.members,t.premium,t.productDetails,t.ws_agentid,t.status,t.isJunk,t.leadDescription,t.currentAllocatedId,t.createdBy,t.createdOn,t.updatedOn,t.jsonAllData from leads_cron as t $wherecon $condfilter t.leadId > 0 order by t.leadId DESC $limitCond")->queryAll();
  305. }else{
  306. if(isset($getleadSourceId) && !empty($getleadSourceId))
  307. {
  308. $condfilter .= "t.leadSourceId =".$getleadSourceId." AND";
  309. }
  310. if(count($getleadStatusId) > 0){
  311. $getleadStatusId = implode(",",$getleadStatusId);
  312. $primaryDisposition=Yii::app()->db->createCommand("select leadStatus.leadStatus,leadStatusId from leadStatus where parentId IN (".@$getleadStatusId.") ")->queryAll();
  313. if(count($primaryDisposition) > 0){
  314. for($w=0;$w<count($primaryDisposition);$w++){
  315. @$PrimaryDispositionIds[] = @$primaryDisposition[$w]['leadStatusId'];
  316. }
  317. } else {
  318. @$PrimaryDispositionIds[] = '';
  319. }
  320. @$PrimaryDispositionIds = implode(",",@$PrimaryDispositionIds);
  321. } else {
  322. @$PrimaryDispositionIds = '';
  323. }
  324. if(isset($PrimaryDispositionIds) && !empty($PrimaryDispositionIds))
  325. {
  326. $condfilter .= "t.leadStatusId IN (".@$PrimaryDispositionIds.") AND ";
  327. }
  328. if(isset($condfilter) && !empty($condfilter)){
  329. $wherecon = "WHERE ";
  330. } else {
  331. $wherecon = "";
  332. }
  333. $data=Yii::app()->db->createCommand("select t.leadId,t.name,t.mobile,t.email,t.address,t.members,t.premium,t.productDetails,t.ws_agentid,t.status,t.isJunk,t.leadDescription,t.currentAllocatedId,t.createdBy,t.createdOn,t.updatedOn,t.jsonAllData from leads_cron as t $wherecon $condfilter t.leadId > 0 order by t.leadId DESC $limitCond ")->queryAll();
  334. }
  335. if(count($data)>0){
  336. $file_name = "lms" . "_" . date("Y-m-d_H-i", time()) . ".csv";
  337. header('Content-Type: text/html; charset=utf-8');
  338. header("Content-type: application/octet-stream");
  339. header("Content-Disposition: attachment; filename=\"$file_name\"");
  340. header("Cache-Control: cache, must-revalidate");
  341. header("Pragma: public");
  342. $col = array(
  343. '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', 'Upload Date','Last Modified Date','Agent-Id');
  344. foreach ($col as $key => $value) {
  345. echo $value . ",";
  346. }
  347. echo "\n";
  348. $i=1;
  349. foreach ($data as $key => $value) {
  350. $jsonArray = json_decode($value['jsonAllData']);
  351. $state = $jsonArray->state;
  352. $city = $jsonArray->city;
  353. $product = $jsonArray->product;
  354. $leadStatus = $jsonArray->leadStatus;
  355. $leadSource = $jsonArray->leadSource;
  356. $leadStage = $jsonArray->leadStage;
  357. $ActivityDescription = $jsonArray->ActivityDescription;
  358. $owner = $jsonArray->owner;
  359. $customerType = $jsonArray->customerType;
  360. $policyType = $jsonArray->policyType;
  361. $planType = $jsonArray->planType;
  362. $campaign = $jsonArray->campaign;
  363. // $sqlDesc = "select group_concat(description) as ActivityDescription from leadFollowup where leadId=".@$value["leadId"]." ";
  364. // $dataDesc=Yii::app()->db->createCommand($sqlDesc)->queryAll();
  365. // $leadActivity = @$dataDesc[0]['ActivityDescription']?str_replace(",","/",@$dataDesc[0]['ActivityDescription']):'';
  366. if($value['currentAllocatedId']==$value['createdBy']){
  367. $owner = $owner."(C)";
  368. } else {
  369. $owner = $owner;
  370. }
  371. $uploadDate = date("d-M-Y H-i-s A",$value['createdOn']);
  372. $lastModifieddate = date("d-M-Y H-i-s A",$value['updatedOn']);
  373. echo $i++ . ",";
  374. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["name"])) . ",";
  375. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value["mobile"])) . ",";
  376. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$value["email"])) . ",";
  377. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$value["address"])) . ",";
  378. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$city)) . ",";
  379. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$state)) . ",";
  380. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value["members"])) . ",";
  381. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value["premium"])) . ",";
  382. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value['productDetails'])) . ",";
  383. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$leadStatus)) . ",";
  384. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value["status"])) . ",";
  385. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value["isJunk"])) . ",";
  386. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$leadSource)) . ",";
  387. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$leadStage)) . ",";
  388. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$value["leadDescription"])) . ",";
  389. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$ActivityDescription)) . ",";
  390. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$customerType)) . ",";
  391. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$product)) . ",";
  392. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$policyType)) . ",";
  393. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$planType)) . ",";
  394. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$campaign)) . ",";
  395. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value["leadSourceCode"])) . ",";
  396. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$owner)) . ",";
  397. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$uploadDate)) . ",";
  398. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$lastModifieddate)) . ",";
  399. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value["ws_agentid"])) . ",";
  400. echo "\n";
  401. }
  402. }
  403. else{
  404. $this->redirect('index.php?r=reports/reports');
  405. //$dataProvider=new CActiveDataProvider('LeadCronReport', array('criteria'=>@$criteria,));
  406. //$this->render('reports',array('model'=>$model,'dataProvider'=>$dataProvider));
  407. }
  408. }
  409. public function getLeadDescription($leadId){
  410. $records=Yii::app()->db->createCommand("select leadDescription from lead where leadId='".@$leadId."' ")->queryAll();
  411. if(count($records) > 0) {
  412. for($i=0;$i<count($records);$i++){
  413. $record[] = @$records[$i]['leadDescription'];
  414. }
  415. } else {
  416. echo "";
  417. }
  418. if( count(@$record) > 1){
  419. echo "<label title='".implode(',',$record)."'><a href='#'>".substr(implode(',',$record),0,5)."...</a></label>";
  420. } else if( count(@$record) == 1) {
  421. echo "<label title='".implode(',',@$record)."'><a href='#'>".implode(',',$record)."</a></label>";
  422. } else {
  423. echo "";
  424. }
  425. //echo explode(',',$agentId);
  426. }
  427. public function getLeadActivityDescription($leadId){
  428. $records=Yii::app()->db->createCommand("select description from leadFollowup where leadId='".@$leadId."' ")->queryAll();
  429. if(count($records) > 0) {
  430. for($i=0;$i<count($records);$i++){
  431. $record[] = @$records[$i]['description'];
  432. }
  433. } else {
  434. echo "";
  435. }
  436. if( count(@$record) > 1){
  437. echo "<label title='".implode(',',$record)."'><a href='#'>".substr(implode(',',$record),0,5)."...</a></label>";
  438. } else if( count(@$record) == 1) {
  439. echo "<label title='".implode(',',@$record)."'><a href='#'>".substr(implode(',',$record),0,5)."...</a></label>";
  440. } else {
  441. echo "";
  442. }
  443. //echo explode(',',$agentId);
  444. }
  445. public function getLeadActivityDescriptionExcel($leadId){
  446. $records=Yii::app()->db->createCommand("select description from leadFollowup where leadId='".@$leadId."' ")->queryAll();
  447. if(count($records) > 0) {
  448. for($i=0;$i<count($records);$i++){
  449. $record[] = @$records[$i]['description'];
  450. }
  451. } else {
  452. echo "";
  453. }
  454. if( count(@$record) > 1){
  455. echo implode(',',$record);
  456. } else if( count(@$record) == 1) {
  457. echo implode(',',$record);
  458. } else {
  459. echo "";
  460. }
  461. //echo explode(',',$agentId);
  462. }
  463. public function actionCheckanddelete(){
  464. $reportmodel=Lead::model()->findAll();
  465. print_r($reportmodel);
  466. die;
  467. }
  468. function actioncroneJobForReport(){
  469. $sourcewiseDetails=Yii::app()->db->createCommand("select * from leads_cron_history where id='lead_updated_on' ")->queryAll();
  470. $sourcewiseDetails[0]['updatedOn'];
  471. $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 ";
  472. $dataUpdatedOn=Yii::app()->db->createCommand($queryUpdatedOn)->queryAll();
  473. $updateleads_cron_history = " update leads_cron_history set updated_ts = '".date('Y-m-d H:i:s')."',updatedOn = '".time()."' where id='lead_updated_on' ";
  474. $executeQueryder=Yii::app()->db->createCommand($updateleads_cron_history)->execute();
  475. //$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 ";
  476. //$dataCreatedOn=Yii::app()->db->createCommand($queryCreatedOn)->queryAll();
  477. $insertcount=0;
  478. $updatecount=0;
  479. if(count($dataUpdatedOn) > 0){
  480. foreach ($dataUpdatedOn as $key => $value) {
  481. $owner = @$value['firstName']?(@$value['firstName']." ".@$value['lastName']):"NA";
  482. $sqlDesc = "select group_concat(description) as ActivityDescription from renewalleadFollowup where leadId=".@$value["leadId"]." ";
  483. $dataDesc=Yii::app()->db->createCommand($sqlDesc)->queryAll();
  484. $leadActivity = @$dataDesc[0]['ActivityDescription']?str_replace(",",":",@$dataDesc[0]['ActivityDescription']):'';
  485. $state = @$value["state"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["state"])):'NA';
  486. $city = @$value["city"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["city"])):'NA';
  487. $customerType = @$value["customerType"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["customerType"])):'NA';
  488. $productName = @$value["productName"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["productName"])):'NA';
  489. $policyType = @$value["policyType"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["policyType"])):'NA';
  490. $planType = @$value["planType"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["planType"])):'NA';
  491. $campaignName = @$value["campaignName"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["campaignName"])):'NA';
  492. $leadSourceTitle = @$value["leadSourceTitle"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["leadSourceTitle"])):'NA';
  493. $leadStatus = @$value["leadStatus"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["leadStatus"])):'NA';
  494. $leadStage = @$value["leadStage"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["leadStage"])):'NA';
  495. $owner = @$owner?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$owner)):'NA';
  496. $agntName = @$value["agntName"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["agntName"])):'NA';
  497. $leadActivity = @$leadActivity?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$leadActivity)):'NA';
  498. $newarray = array(
  499. 'state' => $state,
  500. 'city' => $city,
  501. 'customerType' => $customerType,
  502. 'product' => $productName,
  503. 'policyType' => $policyType,
  504. 'planType' => $planType,
  505. 'campaign' => $campaignName,
  506. 'leadSource' => $leadSourceTitle,
  507. 'leadStatus' => $leadStatus,
  508. 'leadStage' => $leadStage,
  509. 'owner' => addslashes($owner),
  510. 'agntName' => $agntName,
  511. 'ActivityDescription' => str_replace("'","`",$leadActivity)
  512. );
  513. $jsonData = json_encode($newarray);
  514. //$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'].") ";
  515. if($value['createdOn'] >= $sourcewiseDetails[0]['updatedOn']){
  516. $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') ";
  517. $executeQuery4=Yii::app()->db->createCommand($insertQuery)->execute();
  518. //echo "<br><br>" .$insertQuery;
  519. $insertcount++;
  520. } else if($value['updatedOn'] >= $sourcewiseDetails[0]['updatedOn']){
  521. $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']." ";
  522. $executeQuery2=Yii::app()->db->createCommand($updateQuery)->execute();
  523. //echo "<br><br>" .$updateQuery;
  524. $updatecount++;
  525. }
  526. }
  527. }
  528. echo "insert count=".$insertcount." and update count=".$updatecount;
  529. }
  530. function actioncroneFirstTime(){
  531. $startId = @$_REQUEST['startId'];
  532. $endId = @$_REQUEST['endId'];
  533. if(empty($startId) || empty($endId)){
  534. echo "parameter missing";
  535. die;
  536. }
  537. if($startId > $endId){
  538. echo "start Limit can not be greater or equal to end Limit";
  539. die;
  540. }
  541. $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 ";
  542. $data=Yii::app()->db->createCommand($query)->queryAll();
  543. $updateleads_cron_history = " update leads_cron_history set updated_ts = '".date('Y-m-d H:i:s')."',updatedOn = '".time()."' where id='lead_updated_on' ";
  544. $executeQuery=Yii::app()->db->createCommand($updateleads_cron_history)->execute();
  545. //$r=0;
  546. foreach ($data as $key => $value) {
  547. $owner = @$value['firstName']?(@$value['firstName']." ".@$value['lastName']):"NA";
  548. $sqlDesc = "select group_concat(description) as ActivityDescription from renewalleadFollowup where leadId=".@$value["leadId"]." ";
  549. $dataDesc=Yii::app()->db->createCommand($sqlDesc)->queryAll();
  550. $leadActivity = @$dataDesc[0]['ActivityDescription']?str_replace(",",":",@$dataDesc[0]['ActivityDescription']):'';
  551. $state = @$value["state"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["state"])):'NA';
  552. $city = @$value["city"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["city"])):'NA';
  553. $customerType = @$value["customerType"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["customerType"])):'NA';
  554. $productName = @$value["productName"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["productName"])):'NA';
  555. $policyType = @$value["policyType"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["policyType"])):'NA';
  556. $planType = @$value["planType"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["planType"])):'NA';
  557. $campaignName = @$value["campaignName"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["campaignName"])):'NA';
  558. $leadSourceTitle = @$value["leadSourceTitle"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["leadSourceTitle"])):'NA';
  559. $leadStatus = @$value["leadStatus"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["leadStatus"])):'NA';
  560. $leadStage = @$value["leadStage"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["leadStage"])):'NA';
  561. $owner = @$owner?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$owner)):'NA';
  562. $agntName = @$value["agntName"]?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["agntName"])):'NA';
  563. $leadActivity = @$leadActivity?stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$leadActivity)):'NA';
  564. $newarray = array(
  565. 'state' => $state,
  566. 'city' => $city,
  567. 'customerType' => addslashes($customerType),
  568. 'product' => addslashes($productName),
  569. 'policyType' => addslashes($policyType),
  570. 'planType' => addslashes($planType),
  571. 'campaign' => addslashes($campaignName),
  572. 'leadSource' => addslashes($leadSourceTitle),
  573. 'leadStatus' => addslashes($leadStatus),
  574. 'leadStage' => addslashes($leadStage),
  575. 'owner' => addslashes($owner),
  576. 'agntName' => addslashes($agntName),
  577. 'ActivityDescription' => str_replace("'","`",$leadActivity)
  578. );
  579. $jsonData = json_encode($newarray);
  580. $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') ";
  581. $executeQuerys=Yii::app()->db->createCommand($insertQuery)->execute();
  582. //echo $value['leadId']."<br>";
  583. // $r++;
  584. }
  585. }
  586. public function actionagentwisetotalcalls(){
  587. $time = time();
  588. $parser = new CHtmlPurifier();
  589. $afterMonth = $parser->purify(intval(@$_REQUEST['month']));
  590. $afterDate = $parser->purify(intval(@$_REQUEST['date']));
  591. $afterYear = $parser->purify(intval(@$_REQUEST['year']));
  592. if(isset($afterMonth) && !empty($afterMonth) && isset($afterDate) && !empty($afterDate) && isset($afterYear) && !empty($afterYear)){
  593. $start = mktime(0, 0, 0,$afterMonth,$afterDate,$afterYear);
  594. $end = mktime(23, 59, 59,$afterMonth,$afterDate,$afterYear);
  595. } else {
  596. $start = mktime(0, 0, 0);
  597. $end = mktime(23, 59, 59);
  598. }
  599. $date = date('d_M_Y',$start)."_";
  600. $host = '10.216.6.59'; // MYSQL database host adress
  601. $db = 'lms'; // MYSQL database name
  602. $user = 'root'; // Mysql Datbase user
  603. $pass = '0kwp6aNR'; // Mysql Datbase password
  604. $link=mysql_connect($host,$user,$pass);
  605. mysql_select_db($db,$link);
  606. $table='report_agentwisetotalcalls';
  607. $filename = "filesystem/".$date.$table.'.csv';
  608. $csv_terminated = "\n";
  609. $csv_separator = ",";
  610. $csv_enclosed = '"';
  611. $csv_escaped = "\\";
  612. $totalleadstatusids = '7,8,9,10,37,38,11,12,42,43,13,14,15,16,17,18,19,30,21,22,23,24,25,26,27,28,29,30,33,39,43';
  613. mysql_query("insert into report_info (id,type,filename,createdOn,createdBy,updatedOn,updatedBy) values('','agentwisetotalcalls','".@$filename."','".@$time."','".@$_SESSION['id']."','".@$time."','".@$_SESSION['id']."')");
  614. $chktableExist = mysql_query('DROP TABLE IF EXISTS '.$table.' ') or die(mysql_error());
  615. $tableres ='create table IF NOT EXISTS '.$table.' as SELECT
  616. user.userName as `Caller Name`,
  617. SUM(CASE WHEN lead.currentAllocatedId=user.id AND lead.leadStatusId IN ('.@$totalleadstatusids.') THEN 1 ELSE 0 END) AS `Total Diposed`,
  618. SUM(CASE WHEN LS.`leadStatusId` = 7 THEN 1 ELSE 0 END) AS `Sale Done`,
  619. SUM(CASE WHEN LS.`leadStatusId` = 8 THEN 1 ELSE 0 END) AS `Follow Up`,
  620. SUM(CASE WHEN LS.`leadStatusId` = 9 THEN 1 ELSE 0 END) AS `Do Not Call - Will Buy self on Website`,
  621. SUM(CASE WHEN LS.`leadStatusId` = 10 THEN 1 ELSE 0 END) AS `Duplicate - Already In Talk With Team`,
  622. SUM(CASE WHEN LS.`leadStatusId` = 37 THEN 1 ELSE 0 END) AS `In Contact with Oflline Agent`,
  623. SUM(CASE WHEN LS.`leadStatusId` = 38 THEN 1 ELSE 0 END) AS `In Touch With Other Partner`,
  624. SUM(CASE WHEN LS.`leadStatusId` = 11 THEN 1 ELSE 0 END) AS `Short Hangup`,
  625. SUM(CASE WHEN LS.`leadStatusId` = 12 THEN 1 ELSE 0 END) AS `Call Later`,
  626. SUM(CASE WHEN LS.`leadStatusId` = 42 THEN 1 ELSE 0 END) AS `Ringing Less Than Five Tries`,
  627. SUM(CASE WHEN LS.`leadStatusId` = 43 THEN 1 ELSE 0 END) AS `Switched Off Less than Five Tries`,
  628. SUM(CASE WHEN LS.`leadStatusId` = 13 THEN 1 ELSE 0 END) AS `Not Interested - Fund Problem`,
  629. SUM(CASE WHEN LS.`leadStatusId` = 14 THEN 1 ELSE 0 END) AS `Just Checking Website`,
  630. SUM(CASE WHEN LS.`leadStatusId` = 15 THEN 1 ELSE 0 END) AS `Not Interested - Insured From Employer`,
  631. SUM(CASE WHEN LS.`leadStatusId` = 16 THEN 1 ELSE 0 END) AS `Not Interested - High Premium`,
  632. SUM(CASE WHEN LS.`leadStatusId` = 17 THEN 1 ELSE 0 END) AS `Under Age`,
  633. SUM(CASE WHEN LS.`leadStatusId` = 18 THEN 1 ELSE 0 END) AS `Not Visited Website`,
  634. SUM(CASE WHEN LS.`leadStatusId` = 19 THEN 1 ELSE 0 END) AS `Do Not Call`,
  635. SUM(CASE WHEN LS.`leadStatusId` = 20 THEN 1 ELSE 0 END) AS `Not Interested - General`,
  636. SUM(CASE WHEN LS.`leadStatusId` = 21 THEN 1 ELSE 0 END) AS `Over Age`,
  637. SUM(CASE WHEN LS.`leadStatusId` = 22 THEN 1 ELSE 0 END) AS `Not Interested - Already Insured`,
  638. SUM(CASE WHEN LS.`leadStatusId` = 23 THEN 1 ELSE 0 END) AS `Duplicate Data - Not Interested`,
  639. SUM(CASE WHEN LS.`leadStatusId` = 24 THEN 1 ELSE 0 END) AS `Not Eligible - PED`,
  640. SUM(CASE WHEN LS.`leadStatusId` = 25 THEN 1 ELSE 0 END) AS `Not Interested - Govt. Employee`,
  641. SUM(CASE WHEN LS.`leadStatusId` = 26 THEN 1 ELSE 0 END) AS `Not Interested - Senior Citizen`,
  642. SUM(CASE WHEN LS.`leadStatusId` = 27 THEN 1 ELSE 0 END) AS `Wrong Number`,
  643. SUM(CASE WHEN LS.`leadStatusId` = 28 THEN 1 ELSE 0 END) AS `Customer Not Available`,
  644. SUM(CASE WHEN LS.`leadStatusId` = 29 THEN 1 ELSE 0 END) AS `Language Barrier`,
  645. SUM(CASE WHEN LS.`leadStatusId` = 30 THEN 1 ELSE 0 END) AS `No Response`,
  646. SUM(CASE WHEN LS.`leadStatusId` = 33 THEN 1 ELSE 0 END) AS `Invalid Number`,
  647. SUM(CASE WHEN LS.`leadStatusId` = 36 THEN 1 ELSE 0 END) AS `Junk`,
  648. SUM(CASE WHEN LS.`leadStatusId` = 39 THEN 1 ELSE 0 END) AS `Ringing no response after five tries`,
  649. SUM(CASE WHEN LS.`leadStatusId` = 43 THEN 1 ELSE 0 END) AS `Switched Off/ Not Reachable after 5 tries`
  650. FROM `lead` join user on user.id=lead.currentAllocatedId left join leadStatus LS on LS.leadStatusId=lead.leadStatusId where lead.leadStatusId !=36 AND lead.updatedOn >= "'.@$start.'" and lead.updatedOn <= "'.@$end.'" group by lead.currentAllocatedId';
  651. $esx = mysql_query($tableres) or die(mysql_error());
  652. $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`)
  653. 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."";
  654. mysql_query($queryforinsert);
  655. $sql_query = "select * from $table";
  656. // Gets the data from the database
  657. $result = mysql_query($sql_query) or die(mysql_error());
  658. $fields_cnt = mysql_num_fields($result);
  659. $schema_insert = '';
  660. for ($i = 0; $i < $fields_cnt; $i++)
  661. {
  662. $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
  663. stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
  664. $schema_insert .= $l;
  665. $schema_insert .= $csv_separator;
  666. } // end for
  667. $out = trim(substr($schema_insert, 0, -1));
  668. $out .= $csv_terminated;
  669. // Format the data
  670. while ($row = mysql_fetch_array($result))
  671. {
  672. $schema_insert = '';
  673. for ($j = 0; $j < $fields_cnt; $j++)
  674. {
  675. if ($row[$j] == '0' || $row[$j] != '')
  676. {
  677. if ($csv_enclosed == '')
  678. {
  679. $schema_insert .= $row[$j];
  680. } else
  681. {
  682. $schema_insert .= $csv_enclosed .
  683. str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
  684. }
  685. } else
  686. {
  687. $schema_insert .= '';
  688. }
  689. if ($j < $fields_cnt - 1)
  690. {
  691. $schema_insert .= $csv_separator;
  692. }
  693. } // end for
  694. $out .= $schema_insert;
  695. $out .= $csv_terminated;
  696. } // end while
  697. /// header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
  698. //header("Content-Length: " . strlen($out));
  699. // Output to browser with appropriate mime type, you choose ;)
  700. // header("Content-Disposition: attachment; filename=$filename");
  701. //header("Content-type: text/x-csv");
  702. $fd = fopen ($filename, "w");
  703. fputs($fd, $out);
  704. fclose($fd);
  705. echo "success";
  706. //header("Content-type: text/csv");
  707. //header("Content-type: application/csv");
  708. //echo $out;
  709. exit;
  710. }
  711. public function actionagentfreshleadsdisposition(){
  712. /* $date = date('d_M_Y')."_";
  713. $start = mktime(0, 0, 0);
  714. $end = mktime(23, 59, 59);
  715. */
  716. ini_set('max_input_time', 2400);
  717. ini_set('max_execution_time', 2400);
  718. $parser = new CHtmlPurifier();
  719. $afterMonth = $parser->purify(intval(@$_REQUEST['month']));
  720. $afterDate = $parser->purify(intval(@$_REQUEST['date']));
  721. $afterYear = $parser->purify(intval(@$_REQUEST['year']));
  722. if(isset($afterMonth) && !empty($afterMonth) && isset($afterDate) && !empty($afterDate) && isset($afterYear) && !empty($afterYear)){
  723. $start = mktime(0, 0, 0,$afterMonth,$afterDate,$afterYear);
  724. $end = mktime(23, 59, 59,$afterMonth,$afterDate,$afterYear);
  725. } else {
  726. $start = mktime(0, 0, 0);
  727. $end = mktime(23, 59, 59);
  728. }
  729. $time = time();
  730. $date = date('d_M_Y',$start).'_';
  731. $host = '10.216.6.59'; // MYSQL database host adress
  732. $db = 'lms'; // MYSQL database name
  733. $user = 'root'; // Mysql Datbase user
  734. $pass = '0kwp6aNR'; // Mysql Datbase password
  735. $link=mysql_connect($host,$user,$pass);
  736. mysql_select_db($db,$link);
  737. $table='report_agentfreshleadsdisposition';
  738. $filename = "filesystem/".$date.$table.'.csv';
  739. $csv_terminated = "\n";
  740. $csv_separator = ",";
  741. $csv_enclosed = '"';
  742. $csv_escaped = "\\";
  743. $time = time();
  744. mysql_query("insert into report_info (id,type,filename,createdOn,createdBy,updatedOn,updatedBy) values('','agentfreshleadsdisposition','".@$filename."','".@$time."','".@$_SESSION['id']."','".@$time."','".@$_SESSION['id']."')");
  745. $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';
  746. $chktableExist = mysql_query('DROP TABLE IF EXISTS '.$table.' ') or die(mysql_error());
  747. $tableres ='create table IF NOT EXISTS '.$table.' as SELECT
  748. user.userName as `Caller Name`,
  749. SUM(CASE WHEN lead.currentAllocatedId=user.id THEN 1 ELSE 0 END) AS `Total Assigned`,
  750. SUM(CASE WHEN lead.currentAllocatedId=user.id AND lead.leadStatusId NOT IN ('.@$totalleadstatusids.') THEN 1 ELSE 0 END) AS `No Update`,
  751. SUM(CASE WHEN lead.currentAllocatedId=user.id AND lead.leadStatusId IN ('.@$totalleadstatusids.') THEN 1 ELSE 0 END) AS `Total Diposed`,
  752. SUM(CASE WHEN LS.`leadStatusId` = 7 THEN 1 ELSE 0 END) AS `Sale Done`,
  753. SUM(CASE WHEN LS.`leadStatusId` = 8 THEN 1 ELSE 0 END) AS `Follow Up`,
  754. SUM(CASE WHEN LS.`leadStatusId` = 9 THEN 1 ELSE 0 END) AS `Do Not Call - Will Buy self on Website`,
  755. SUM(CASE WHEN LS.`leadStatusId` = 10 THEN 1 ELSE 0 END) AS `Duplicate - Already In Talk With Team`,
  756. SUM(CASE WHEN LS.`leadStatusId` = 37 THEN 1 ELSE 0 END) AS `In Contact with Oflline Agent`,
  757. SUM(CASE WHEN LS.`leadStatusId` = 38 THEN 1 ELSE 0 END) AS `In Touch With Other Partner`,
  758. SUM(CASE WHEN LS.`leadStatusId` = 11 THEN 1 ELSE 0 END) AS `Short Hangup`,
  759. SUM(CASE WHEN LS.`leadStatusId` = 12 THEN 1 ELSE 0 END) AS `Call Later`,
  760. SUM(CASE WHEN LS.`leadStatusId` = 42 THEN 1 ELSE 0 END) AS `Ringing Less Than Five Tries`,
  761. SUM(CASE WHEN LS.`leadStatusId` = 43 THEN 1 ELSE 0 END) AS `Switched Off Less than Five Tries`,
  762. SUM(CASE WHEN LS.`leadStatusId` = 13 THEN 1 ELSE 0 END) AS `Not Interested - Fund Problem`,
  763. SUM(CASE WHEN LS.`leadStatusId` = 14 THEN 1 ELSE 0 END) AS `Just Checking Website`,
  764. SUM(CASE WHEN LS.`leadStatusId` = 15 THEN 1 ELSE 0 END) AS `Not Interested - Insured From Employer`,
  765. SUM(CASE WHEN LS.`leadStatusId` = 16 THEN 1 ELSE 0 END) AS `Not Interested - High Premium`,
  766. SUM(CASE WHEN LS.`leadStatusId` = 17 THEN 1 ELSE 0 END) AS `Under Age`,
  767. SUM(CASE WHEN LS.`leadStatusId` = 18 THEN 1 ELSE 0 END) AS `Not Visited Website`,
  768. SUM(CASE WHEN LS.`leadStatusId` = 19 THEN 1 ELSE 0 END) AS `Do Not Call`,
  769. SUM(CASE WHEN LS.`leadStatusId` = 20 THEN 1 ELSE 0 END) AS `Not Interested - General`,
  770. SUM(CASE WHEN LS.`leadStatusId` = 21 THEN 1 ELSE 0 END) AS `Over Age`,
  771. SUM(CASE WHEN LS.`leadStatusId` = 22 THEN 1 ELSE 0 END) AS `Not Interested - Already Insured`,
  772. SUM(CASE WHEN LS.`leadStatusId` = 23 THEN 1 ELSE 0 END) AS `Duplicate Data - Not Interested`,
  773. SUM(CASE WHEN LS.`leadStatusId` = 24 THEN 1 ELSE 0 END) AS `Not Eligible - PED`,
  774. SUM(CASE WHEN LS.`leadStatusId` = 25 THEN 1 ELSE 0 END) AS `Not Interested - Govt. Employee`,
  775. SUM(CASE WHEN LS.`leadStatusId` = 26 THEN 1 ELSE 0 END) AS `Not Interested - Senior Citizen`,
  776. SUM(CASE WHEN LS.`leadStatusId` = 27 THEN 1 ELSE 0 END) AS `Wrong Number`,
  777. SUM(CASE WHEN LS.`leadStatusId` = 28 THEN 1 ELSE 0 END) AS `Customer Not Available`,
  778. SUM(CASE WHEN LS.`leadStatusId` = 29 THEN 1 ELSE 0 END) AS `Language Barrier`,
  779. SUM(CASE WHEN LS.`leadStatusId` = 30 THEN 1 ELSE 0 END) AS `No Response`,
  780. SUM(CASE WHEN LS.`leadStatusId` = 33 THEN 1 ELSE 0 END) AS `Invalid Number`,
  781. SUM(CASE WHEN LS.`leadStatusId` = 36 THEN 1 ELSE 0 END) AS `Junk`,
  782. SUM(CASE WHEN LS.`leadStatusId` = 39 THEN 1 ELSE 0 END) AS `Ringing no response after five tries`,
  783. SUM(CASE WHEN LS.`leadStatusId` = 43 THEN 1 ELSE 0 END) AS `Switched Off/ Not Reachable after 5 tries`
  784. 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';
  785. $esx = mysql_query($tableres) or die(mysql_error());
  786. $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`)
  787. 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."";
  788. mysql_query($queryforinsert);
  789. $sql_query = "select * from $table";
  790. // Gets the data from the database
  791. $result = mysql_query($sql_query);
  792. $fields_cnt = mysql_num_fields($result);
  793. $schema_insert = '';
  794. for ($i = 0; $i < $fields_cnt; $i++)
  795. {
  796. $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
  797. stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
  798. $schema_insert .= $l;
  799. $schema_insert .= $csv_separator;
  800. } // end for
  801. $out = trim(substr($schema_insert, 0, -1));
  802. $out .= $csv_terminated;
  803. // Format the data
  804. while ($row = mysql_fetch_array($result))
  805. {
  806. $schema_insert = '';
  807. for ($j = 0; $j < $fields_cnt; $j++)
  808. {
  809. if ($row[$j] == '0' || $row[$j] != '')
  810. {
  811. if ($csv_enclosed == '')
  812. {
  813. $schema_insert .= $row[$j];
  814. } else
  815. {
  816. $schema_insert .= $csv_enclosed .
  817. str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
  818. }
  819. } else
  820. {
  821. $schema_insert .= '';
  822. }
  823. if ($j < $fields_cnt - 1)
  824. {
  825. $schema_insert .= $csv_separator;
  826. }
  827. } // end for
  828. $out .= $schema_insert;
  829. $out .= $csv_terminated;
  830. } // end while
  831. $fd = fopen ($filename, "w");
  832. fputs($fd, $out);
  833. fclose($fd);
  834. echo "success";
  835. //header("Content-type: text/csv");
  836. //header("Content-type: application/csv");
  837. //echo $out;
  838. exit;
  839. }
  840. public function actioncampaignwisedispositiondaily(){
  841. $time = time();
  842. $parser = new CHtmlPurifier();
  843. $afterMonth = $parser->purify(intval(@$_REQUEST['month']));
  844. $afterDate = $parser->purify(intval(@$_REQUEST['date']));
  845. $afterYear = $parser->purify(intval(@$_REQUEST['year']));
  846. if(isset($afterMonth) && !empty($afterMonth) && isset($afterDate) && !empty($afterDate) && isset($afterYear) && !empty($afterYear)){
  847. $start = mktime(0, 0, 0,$afterMonth,$afterDate,$afterYear);
  848. $end = mktime(23, 59, 59,$afterMonth,$afterDate,$afterYear);
  849. } else {
  850. $start = mktime(0, 0, 0);
  851. $end = mktime(23, 59, 59);
  852. }
  853. $date = date('d_M_Y',$start)."_";
  854. $host = '10.216.6.59'; // MYSQL database host adress
  855. $db = 'lms'; // MYSQL database name
  856. $user = 'root'; // Mysql Datbase user
  857. $pass = '0kwp6aNR'; // Mysql Datbase password
  858. $link=mysql_connect($host,$user,$pass);
  859. mysql_select_db($db,$link);
  860. $table='report_campaignwisedispositiondaily';
  861. $filename = "filesystem/".$date.$table.'.csv';
  862. $csv_terminated = "\n";
  863. $csv_separator = ",";
  864. $csv_enclosed = '"';
  865. $csv_escaped = "\\";
  866. mysql_query("insert into report_info (id,type,filename,createdOn,createdBy,updatedOn,updatedBy) values('','campaignwisedispositiondaily','".@$filename."','".@$time."','".@$_SESSION['id']."','".@$time."','".@$_SESSION['id']."')");
  867. $chktableExist = mysql_query('DROP TABLE IF EXISTS '.$table.' ') or die(mysql_error());
  868. $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`,
  869. SUM(CASE WHEN L.`leadStatusId` = 7 THEN 1 ELSE 0 END) AS `Sale Done`,
  870. SUM(CASE WHEN L.`leadStatusId` = 8 THEN 1 ELSE 0 END) AS `Follow Up`,
  871. SUM(CASE WHEN L.`leadStatusId` = 9 THEN 1 ELSE 0 END) AS `Do Not Call - Will Buy self on Website`,
  872. SUM(CASE WHEN L.`leadStatusId` = 10 THEN 1 ELSE 0 END) AS `Duplicate - Already In Talk With Team`,
  873. SUM(CASE WHEN L.`leadStatusId` = 37 THEN 1 ELSE 0 END) AS `In Contact with Oflline Agent`,
  874. SUM(CASE WHEN L.`leadStatusId` = 38 THEN 1 ELSE 0 END) AS `In Touch With Other Partner`,
  875. SUM(CASE WHEN L.`leadStatusId` = 11 THEN 1 ELSE 0 END) AS `Short Hangup`,
  876. SUM(CASE WHEN L.`leadStatusId` = 12 THEN 1 ELSE 0 END) AS `Call Later`,
  877. SUM(CASE WHEN L.`leadStatusId` = 42 THEN 1 ELSE 0 END) AS `Ringing Less Than Five Tries`,
  878. SUM(CASE WHEN L.`leadStatusId` = 43 THEN 1 ELSE 0 END) AS `Switched Off Less than Five Tries`,
  879. SUM(CASE WHEN L.`leadStatusId` = 13 THEN 1 ELSE 0 END) AS `Not Interested - Fund Problem`,
  880. SUM(CASE WHEN L.`leadStatusId` = 14 THEN 1 ELSE 0 END) AS `Just Checking Website`,
  881. SUM(CASE WHEN L.`leadStatusId` = 15 THEN 1 ELSE 0 END) AS `Not Interested - Insured From Employer`,
  882. SUM(CASE WHEN L.`leadStatusId` = 16 THEN 1 ELSE 0 END) AS `Not Interested - High Premium`,
  883. SUM(CASE WHEN L.`leadStatusId` = 17 THEN 1 ELSE 0 END) AS `Under Age`,
  884. SUM(CASE WHEN L.`leadStatusId` = 18 THEN 1 ELSE 0 END) AS `Not Visited Website`,
  885. SUM(CASE WHEN L.`leadStatusId` = 19 THEN 1 ELSE 0 END) AS `Do Not Call`,
  886. SUM(CASE WHEN L.`leadStatusId` = 20 THEN 1 ELSE 0 END) AS `Not Interested - General`,
  887. SUM(CASE WHEN L.`leadStatusId` = 21 THEN 1 ELSE 0 END) AS `Over Age`,
  888. SUM(CASE WHEN L.`leadStatusId` = 22 THEN 1 ELSE 0 END) AS `Not Interested - Already Insured`,
  889. SUM(CASE WHEN L.`leadStatusId` = 23 THEN 1 ELSE 0 END) AS `Duplicate Data - Not Interested`,
  890. SUM(CASE WHEN L.`leadStatusId` = 24 THEN 1 ELSE 0 END) AS `Not Eligible - PED`,
  891. SUM(CASE WHEN L.`leadStatusId` = 25 THEN 1 ELSE 0 END) AS `Not Interested - Govt. Employee`,
  892. SUM(CASE WHEN L.`leadStatusId` = 26 THEN 1 ELSE 0 END) AS `Not Interested - Senior Citizen`,
  893. SUM(CASE WHEN L.`leadStatusId` = 27 THEN 1 ELSE 0 END) AS `Wrong Number`,
  894. SUM(CASE WHEN L.`leadStatusId` = 28 THEN 1 ELSE 0 END) AS `Customer Not Available`,
  895. SUM(CASE WHEN L.`leadStatusId` = 29 THEN 1 ELSE 0 END) AS `Language Barrier`,
  896. SUM(CASE WHEN L.`leadStatusId` = 30 THEN 1 ELSE 0 END) AS `No Response`,
  897. SUM(CASE WHEN L.`leadStatusId` = 33 THEN 1 ELSE 0 END) AS `Invalid Number`,
  898. SUM(CASE WHEN L.`leadStatusId` = 36 THEN 1 ELSE 0 END) AS `Junk`,
  899. SUM(CASE WHEN L.`leadStatusId` = 39 THEN 1 ELSE 0 END) AS `Ringing no response after five tries`,
  900. SUM(CASE WHEN L.`leadStatusId` = 43 THEN 1 ELSE 0 END) AS `Switched Off/ Not Reachable after 5 tries`
  901. from leadSourceMaster LS left join lead L on L.ws_agentid=LS.leadSourceCode where L.leadStatusId !=36 AND L.updatedOn >= "'.@$start.'" and L.updatedOn <= "'.@$end.'" group by L.leadStatusId,LS.leadSourceCode';
  902. $esx = mysql_query($tableres) or die(mysql_error());
  903. $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`)
  904. 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."";
  905. mysql_query($queryforinsert);
  906. $sql_query = "select * from ".$table."";
  907. // Gets the data from the database
  908. $result = mysql_query($sql_query);
  909. $fields_cnt = mysql_num_fields($result);
  910. $schema_insert = '';
  911. for ($i = 0; $i < $fields_cnt; $i++)
  912. {
  913. $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
  914. stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
  915. $schema_insert .= $l;
  916. $schema_insert .= $csv_separator;
  917. } // end for
  918. $out = trim(substr($schema_insert, 0, -1));
  919. $out .= $csv_terminated;
  920. // Format the data
  921. while ($row = mysql_fetch_array($result))
  922. {
  923. $schema_insert = '';
  924. for ($j = 0; $j < $fields_cnt; $j++)
  925. {
  926. if ($row[$j] == '0' || $row[$j] != '')
  927. {
  928. if ($csv_enclosed == '')
  929. {
  930. $schema_insert .= $row[$j];
  931. } else
  932. {
  933. $schema_insert .= $csv_enclosed .
  934. str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
  935. }
  936. } else
  937. {
  938. $schema_insert .= '';
  939. }
  940. if ($j < $fields_cnt - 1)
  941. {
  942. $schema_insert .= $csv_separator;
  943. }
  944. } // end for
  945. $out .= $schema_insert;
  946. $out .= $csv_terminated;
  947. } // end while
  948. $fd = fopen ($filename, "w");
  949. fputs($fd, $out);
  950. fclose($fd);
  951. echo "success";
  952. //header("Content-type: text/csv");
  953. //header("Content-type: application/csv");
  954. //echo $out;
  955. exit;
  956. }
  957. public function actiondatadumpsameday(){
  958. ini_set('max_input_time', 1200);
  959. ini_set('max_execution_time', 1200);
  960. $parser = new CHtmlPurifier();
  961. $afterMonth = $parser->purify(intval(@$_REQUEST['month']));
  962. $afterDate = $parser->purify(intval(@$_REQUEST['date']));
  963. $afterYear = $parser->purify(intval(@$_REQUEST['year']));
  964. if(isset($afterMonth) && !empty($afterMonth) && isset($afterDate) && !empty($afterDate) && isset($afterYear) && !empty($afterYear)){
  965. $start = mktime(0, 0, 0,$afterMonth,$afterDate,$afterYear);
  966. $end = mktime(23, 59, 59,$afterMonth,$afterDate,$afterYear);
  967. } else {
  968. $start = mktime(0, 0, 0);
  969. $end = mktime(23, 59, 59);
  970. }
  971. $time = time();
  972. $date = date('d_M_Y',$start).'_';
  973. $host = '10.216.6.59'; // MYSQL database host adress
  974. $db = 'lms'; // MYSQL database name
  975. $user = 'root'; // Mysql Datbase user
  976. $pass = '0kwp6aNR'; // Mysql Datbase password
  977. $link=mysql_connect($host,$user,$pass);
  978. mysql_select_db($db,$link);
  979. $table='report_datadumpsameday';
  980. $filename = "filesystem/".$date.$table.'.csv';
  981. $csv_terminated = "\n";
  982. $csv_separator = ",";
  983. $csv_enclosed = '"';
  984. $csv_escaped = "\\";
  985. mysql_query("insert into report_info (id,type,filename,createdOn,createdBy,updatedOn,updatedBy) values('','datadumpsameday','".@$filename."','".@$time."','".@$_SESSION['id']."','".@$time."','".@$_SESSION['id']."')");
  986. $chktableExist = mysql_query('DROP TABLE IF EXISTS '.$table.' ') or die(mysql_error());
  987. mysql_query('set @a:=0');
  988. $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."'";
  989. $esx = mysql_query($tableres) or die(mysql_error());
  990. $sql_query = "select * from $table";
  991. // Gets the data from the database
  992. $result = mysql_query($sql_query);
  993. $fields_cnt = mysql_num_fields($result);
  994. $schema_insert = '';
  995. for ($i = 0; $i < $fields_cnt; $i++)
  996. {
  997. $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
  998. stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
  999. $schema_insert .= $l;
  1000. $schema_insert .= $csv_separator;
  1001. } // end for
  1002. $out = trim(substr($schema_insert, 0, -1));
  1003. $out .= $csv_terminated;
  1004. // Format the data
  1005. while ($row = mysql_fetch_array($result))
  1006. {
  1007. $schema_insert = '';
  1008. for ($j = 0; $j < $fields_cnt; $j++)
  1009. {
  1010. if ($row[$j] == '0' || $row[$j] != '')
  1011. {
  1012. if ($csv_enclosed == '')
  1013. {
  1014. $schema_insert .= $row[$j];
  1015. } else
  1016. {
  1017. $schema_insert .= $csv_enclosed .
  1018. str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
  1019. }
  1020. } else
  1021. {
  1022. $schema_insert .= '';
  1023. }
  1024. if ($j < $fields_cnt - 1)
  1025. {
  1026. $schema_insert .= $csv_separator;
  1027. }
  1028. } // end for
  1029. $out .= $schema_insert;
  1030. $out .= $csv_terminated;
  1031. } // end while
  1032. $fd = fopen ($filename, "w");
  1033. fputs($fd, $out);
  1034. fclose($fd);
  1035. echo "success";
  1036. //header("Content-type: text/csv");
  1037. //header("Content-type: application/csv");
  1038. //echo $out;
  1039. exit;
  1040. }
  1041. public function actiondatadumpmtd(){
  1042. ini_set('max_input_time', 1200);
  1043. ini_set('max_execution_time', 1200);
  1044. $parser = new CHtmlPurifier();
  1045. $afterMonth = $parser->purify(intval(@$_REQUEST['month']));
  1046. $afterYear = $parser->purify(intval(@$_REQUEST['year']));
  1047. if(isset($afterMonth) && !empty($afterMonth) && isset($afterYear) && !empty($afterYear)){
  1048. $start =mktime(0, 0, 0, $afterMonth, 1,$afterYear);
  1049. $end = mktime(23, 59, 0, $afterMonth, date('t', $start),$afterYear);
  1050. } else {
  1051. $start = strtotime('first day of this month', time());
  1052. $end = strtotime('last day of this month', time());
  1053. }
  1054. $date = date('d_M_Y',$start).'_';
  1055. $host = '10.216.6.59'; // MYSQL database host adress
  1056. $db = 'lms'; // MYSQL database name
  1057. $user = 'root'; // Mysql Datbase user
  1058. $pass = '0kwp6aNR'; // Mysql Datbase password
  1059. $link=mysql_connect($host,$user,$pass);
  1060. mysql_select_db($db,$link);
  1061. $table='report_datadumpmtd';
  1062. $filename = "filesystem/".$date.$table.'.csv';
  1063. $csv_terminated = "\n";
  1064. $csv_separator = ",";
  1065. $csv_enclosed = '"';
  1066. $csv_escaped = "\\";
  1067. $time = time();
  1068. mysql_query("insert into report_info (id,type,filename,createdOn,createdBy,updatedOn,updatedBy) values('','datadumpmtd','".@$filename."','".@$time."','".@$_SESSION['id']."','".@$time."','".@$_SESSION['id']."')");
  1069. $chktableExist = mysql_query('DROP TABLE IF EXISTS '.$table.' ') or die(mysql_error());
  1070. // $start = strtotime('first day of this month', time());
  1071. // $end = strtotime('last day of this month', time());
  1072. mysql_query('set @a:=0');
  1073. $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."'";
  1074. $esx = mysql_query($tableres) or die(mysql_error());
  1075. $sql_query = "select * from $table";
  1076. // Gets the data from the database
  1077. $result = mysql_query($sql_query);
  1078. $fields_cnt = mysql_num_fields($result);
  1079. $schema_insert = '';
  1080. for ($i = 0; $i < $fields_cnt; $i++)
  1081. {
  1082. $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
  1083. stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
  1084. $schema_insert .= $l;
  1085. $schema_insert .= $csv_separator;
  1086. } // end for
  1087. $out = trim(substr($schema_insert, 0, -1));
  1088. $out .= $csv_terminated;
  1089. // Format the data
  1090. while ($row = mysql_fetch_array($result))
  1091. {
  1092. $schema_insert = '';
  1093. for ($j = 0; $j < $fields_cnt; $j++)
  1094. {
  1095. if ($row[$j] == '0' || $row[$j] != '')
  1096. {
  1097. if ($csv_enclosed == '')
  1098. {
  1099. $schema_insert .= $row[$j];
  1100. } else
  1101. {
  1102. $schema_insert .= $csv_enclosed .
  1103. str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
  1104. }
  1105. } else
  1106. {
  1107. $schema_insert .= '';
  1108. }
  1109. if ($j < $fields_cnt - 1)
  1110. {
  1111. $schema_insert .= $csv_separator;
  1112. }
  1113. } // end for
  1114. $out .= $schema_insert;
  1115. $out .= $csv_terminated;
  1116. } // end while
  1117. $fd = fopen ($filename, "w");
  1118. fputs($fd, $out);
  1119. fclose($fd);
  1120. echo "success";
  1121. //header("Content-type: text/csv");
  1122. //header("Content-type: application/csv");
  1123. //echo $out;
  1124. exit;
  1125. }
  1126. public function actionreporttest(){
  1127. $maxDays=date('t');
  1128. $date = date('d_M_Y').'_';
  1129. $host = '10.216.6.59'; // MYSQL database host adress
  1130. $db = 'lms'; // MYSQL database name
  1131. $user = 'root'; // Mysql Datbase user
  1132. $pass = '0kwp6aNR'; // Mysql Datbase password
  1133. $link=mysql_connect($host,$user,$pass);
  1134. mysql_select_db($db,$link);
  1135. $table='report_datadumpmtd';
  1136. $query = mysql_query("select leadSourceCode,leadSourceTitle from leadSourceMaster") ;
  1137. $columnName = array();
  1138. $l=0;
  1139. while($l= mysql_fetch_array($query)){
  1140. $columnName[] = $l['leadSourceCode'];
  1141. $columnNameData[] = $l['leadSourceCode'];
  1142. $leadSourceName[] = $l['leadSourceTitle'];
  1143. $l++;
  1144. }
  1145. $columnName=implode(',',$columnName);
  1146. $leadSourceName=implode(',',$leadSourceName);
  1147. if(count($l)>0){
  1148. $file_name = "lms" . "_" . date("Y-m-d_H-i", time()) . ".csv";
  1149. header('Content-Type: text/html; charset=utf-8');
  1150. header("Content-type: application/octet-stream");
  1151. header("Content-Disposition: attachment; filename=\"$file_name\"");
  1152. header("Cache-Control: cache, must-revalidate");
  1153. header("Pragma: public");
  1154. $col = array(
  1155. 'Agent Code','Total',$columnName);
  1156. foreach ($col as $key => $value) {
  1157. echo $value . ",";
  1158. }
  1159. echo "\n";
  1160. $col2 = array(
  1161. 'Agent Name','',$leadSourceName);
  1162. foreach ($col2 as $key => $value) {
  1163. echo $value . ",";
  1164. }
  1165. echo "\n";
  1166. $i=2;
  1167. $col3 = array($columnNameData);
  1168. $f=0;
  1169. $neresult = 0;
  1170. for($y=1;$y<=$maxDays;$y++) {
  1171. $date = $y.date('/m/Y');
  1172. $explodedDate = explode('/',$date);
  1173. $time = strtotime($explodedDate[0]."-".$explodedDate[1]."-".$explodedDate[2]);
  1174. $timePm = strtotime($explodedDate[0]."-".$explodedDate[1]."-".$explodedDate[2])+86399;
  1175. echo $y.date('/M/Y'). ",";
  1176. $quert = mysql_query('select count(*) as total from lead where ws_agentId IN( "'.@$value[0].'","'.@$value[1].'") and updatedOn >= "'.@$time.'" and updatedOn <= "'.@$timePm.'"');
  1177. $resT = mysql_fetch_array($quert);
  1178. $neresult =$neresult+$resT[0];
  1179. echo $resT[0] . ",";
  1180. foreach ($col3 as $key => $value) {
  1181. $quer = mysql_query('select count(*) as total from lead where ws_agentId = "'.@$value[0].'" and updatedOn >= "'.@$time.'" and updatedOn <= "'.@$timePm.'"');
  1182. $res = mysql_fetch_array($quer);
  1183. $quer1 = mysql_query('select count(*) as total from lead where ws_agentId = "'.@$value[1].'" and updatedOn >= "'.@$time.'" and updatedOn <= "'.@$timePm.'"');
  1184. $res1 = mysql_fetch_array($quer1);
  1185. echo $res[0] . ",";
  1186. echo $res1[0] . ",";
  1187. // echo date('d:m:y::h:i:s A',$time) . ",";
  1188. $f++;
  1189. }
  1190. echo "\n";
  1191. }
  1192. echo 'total data'. ",";
  1193. echo $neresult. ",";
  1194. echo "\n";
  1195. }
  1196. }
  1197. public function actiondatamis_old(){
  1198. ini_set('max_input_time', 300);
  1199. ini_set('max_execution_time', 300);
  1200. $host = '10.216.6.59'; // MYSQL database host adress
  1201. $db = 'lms'; // MYSQL database name
  1202. $user = 'root'; // Mysql Datbase user
  1203. $pass = '0kwp6aNR'; // Mysql Datbase password
  1204. $link=mysql_connect($host,$user,$pass);
  1205. mysql_select_db($db,$link);
  1206. $table='report_datamis';
  1207. $chktableExist = mysql_query('DROP TABLE IF EXISTS '.$table.' ') or die(mysql_error());
  1208. $parser = new CHtmlPurifier();
  1209. $afterMonth = $parser->purify(intval(@$_REQUEST['month']));
  1210. $afterYear = $parser->purify(intval(@$_REQUEST['year']));
  1211. if(isset($afterMonth) && !empty($afterMonth) && isset($afterYear) && !empty($afterYear)){
  1212. $start =mktime(0, 0, 0, $afterMonth, 1,$afterYear);
  1213. $end = mktime(23, 59, 0, $afterMonth, date('t', $start),$afterYear);
  1214. } else {
  1215. $start = strtotime('first day of this month', time());
  1216. $end = strtotime('last day of this month', time());
  1217. }
  1218. mysql_query("UPDATE `leadSourceMaster` SET leadSourceTitleReport=REPLACE(leadSourceTitle,' ','')");
  1219. mysql_query("SELECT
  1220. CONCAT(
  1221. 'CREATE TABLE ".$table." (',
  1222. GROUP_CONCAT(DISTINCT
  1223. CONCAT(leadSourceTitleReport, ' VARCHAR(50)')
  1224. SEPARATOR ','),
  1225. ');')
  1226. FROM
  1227. leadSourceMaster
  1228. INTO @sql") or die(mysql_error());
  1229. mysql_query("PREPARE stmt FROM @sql");
  1230. mysql_query("EXECUTE stmt");
  1231. mysql_query("ALTER TABLE ".$table." ADD `AgentName` VARCHAR( 150 ) NOT NULL FIRST ,
  1232. ADD `Total` VARCHAR( 50 ) NOT NULL AFTER `AgentName`");
  1233. $sourcecode = mysql_query("select distinct leadSourceTitleReport as leadSourceTitle,leadsourceCode from leadSourceMaster group by leadSourceTitleReport");
  1234. $row=0;
  1235. $arraymerger = array();
  1236. // $start = strtotime('first day of this month', time());
  1237. // $end = strtotime('last day of this month', time());
  1238. $totalsourcewise = array();
  1239. $totalsourcewisesales = array();
  1240. $totalcontactable = array();
  1241. $conversionpercentage = array();
  1242. $salesIds = '36';
  1243. $contactableids = '7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22';
  1244. $noncontactableids = '27,28,42,43';
  1245. while ($row = mysql_fetch_array($sourcecode)){
  1246. //echo $row['leadsourceCode'];
  1247. $arraymerger[$row['leadsourceCode']] = $row['leadSourceTitle'] ;
  1248. //echo 'select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" THEN 1 ELSE 0 END) AS total from lead'; die;
  1249. $quersum = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" and updatedOn >= "'.@$start.'" and updatedOn <= "'.@$end.'" AND leadStatusId !=36 THEN 1 ELSE 0 END) AS total from lead');
  1250. $querressum = mysql_fetch_assoc($quersum);
  1251. $totalsourcewise[] = $querressum['total'];
  1252. $quersumsales = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" and updatedOn >= "'.@$start.'" and updatedOn <= "'.@$end.'" AND leadStatusId !=36 and leadStatusId IN('.@$salesIds.') THEN 1 ELSE 0 END) AS total from lead');
  1253. $querressumsales = mysql_fetch_assoc($quersumsales);
  1254. $totalsourcewisesales[] = $querressumsales['total'];
  1255. $conversionpercentage[$querressumsales['total']] = $querressum['total'];
  1256. $quersumcontactable = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" and updatedOn >= "'.@$start.'" and updatedOn <= "'.@$end.'" AND leadStatusId !=36 and leadStatusId IN('.@$contactableids.') THEN 1 ELSE 0 END) AS total from lead');
  1257. $querressumcontactable = mysql_fetch_assoc($quersumcontactable);
  1258. $totalcontactable[] = $querressumcontactable['total'];
  1259. $row++; }
  1260. $keys = (implode(",",array_keys($arraymerger)));
  1261. $values = (implode(",",array_values($arraymerger)));
  1262. $q="replace into ".$table." (AgentName,".$values.") values ('AgentCode',".$keys.")";
  1263. mysql_query($q) or die(mysql_error());
  1264. $maxDays=date('t');
  1265. $totalData = 0;
  1266. $totalDatasales = 0;
  1267. $totalDatacontactable = 0;
  1268. for($y=1;$y<=$maxDays;$y++) {
  1269. $date = $y.date('/m/Y');
  1270. $explodedDate = explode('/',$date);
  1271. $time = strtotime($explodedDate[0]."-".$explodedDate[1]."-".$explodedDate[2]);
  1272. $timePm = strtotime($explodedDate[0]."-".$explodedDate[1]."-".$explodedDate[2])+86399;
  1273. $totalcountcode = array();
  1274. $totalcountsales = array();
  1275. $totalcountcontact = array();
  1276. $totalcountcoderes=0;
  1277. foreach($arraymerger as $key=>$values1){
  1278. $quer = mysql_query('select count(*) as total from lead where ws_agentId = "'.@$key.'" and updatedOn >= "'.@$time.'" AND leadStatusId !=36 and updatedOn <= "'.@$timePm.'"');
  1279. $querres = mysql_fetch_assoc($quer);
  1280. $totalcountcode[] = $querres['total'];
  1281. $totalcountcoderes =$querres['total'];
  1282. $salesquery = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$key.'" and updatedOn >= "'.@$time.'" AND leadStatusId !=36 and updatedOn <= "'.@$timePm.'" and leadStatusId IN('.@$salesIds.') THEN 1 ELSE 0 END) as total from lead ');
  1283. $salesqueryres = mysql_fetch_array($salesquery);
  1284. $totalcountsales[] = $salesqueryres['total'];
  1285. $contactquery = mysql_query('select SUM(CASE WHEN ws_agentId = "'.@$key.'" and updatedOn >= "'.@$time.'" AND leadStatusId !=36 and updatedOn <= "'.@$timePm.'" and leadStatusId IN('.@$contactableids.') THEN 1 ELSE 0 END) as total from lead ');
  1286. $contactqueryres = mysql_fetch_array($contactquery);
  1287. $totalcountcontact[] = $contactqueryres['total'];
  1288. }
  1289. $totalsumres = array_sum($totalcountcode);
  1290. $totalsumresales = array_sum($totalcountsales);
  1291. $totalcountcontact = array_sum($totalcountcontact);
  1292. $implodedcountcode = implode(",",$totalcountcode);
  1293. $totalData = $totalData+intval($totalsumres);
  1294. $totalDatasales = $totalDatasales+intval($totalsumresales);
  1295. $totalDatacontactable = $totalDatacontactable+intval($totalcountcontact);
  1296. intval($totalcountcoderes);
  1297. $totalsumsales = array_sum($totalcountsales);
  1298. //print_r($totalcountsales);
  1299. $datequery = "insert into ".$table."(`AgentName`,`Total`,".$values.") values('".$y.date('/M/Y')."',".$totalsumres.",".$implodedcountcode.")";
  1300. mysql_query($datequery);
  1301. }
  1302. $contactper = $totalcontactable;
  1303. $datacontper = $totalsourcewise;
  1304. $datacontpertest = $totalsourcewisesales;
  1305. $totalsourcewise = implode(",",$totalsourcewise);
  1306. $totalsourcewisesales = implode(",",$totalsourcewisesales);
  1307. $totalcontactable = implode(",",$totalcontactable);
  1308. if(@$totalDatacontactable > 0){
  1309. $contactperc = ($totalDatacontactable*100)/$totalData;
  1310. } else {
  1311. $contactperc = '0';
  1312. }
  1313. $contactpervalu =array();
  1314. foreach($contactper as $key2=>$value2){
  1315. if($datacontper[$key2] > 0){
  1316. $contactpervalu[] = '"'.($value2*100)/$datacontper[$key2].'%"';
  1317. } else {
  1318. $contactpervalu[] = "'0%'";
  1319. }
  1320. // $contactpervalu[] = '"'.($value2*100)/$totalDatacontactable.'%"';
  1321. }
  1322. $contactpervalu = implode(",",$contactpervalu);
  1323. if(@$totalData > 0){
  1324. $Datacontributionprec = '100';
  1325. } else {
  1326. $Datacontributionprec = '0';
  1327. }
  1328. $datacontpervalu =array();
  1329. foreach($datacontper as $key4=>$value4){
  1330. if($totalData > 0){
  1331. $datacontpervalu[] = '"'.($value4*100)/$totalData.'%"';
  1332. } else {
  1333. $datacontpervalu[] = "'0%'";
  1334. }
  1335. }
  1336. $datacontpervalu = implode(",",$datacontpervalu);
  1337. $conversionPerkeys = array_keys($conversionpercentage);
  1338. $conversionPervalue = array_values($conversionpercentage);
  1339. $conversionnetres = array();
  1340. for($r=0;$r<count($datacontper);$r++){
  1341. if($datacontper[$r] > 0){
  1342. $conversionnetres[$r] = ($datacontpertest[$r]/$datacontper[$r]).'%"';
  1343. } else {
  1344. $conversionnetres[$r] = "'0%'";
  1345. }
  1346. }
  1347. $conversionpercentagevalu = implode(",",$conversionnetres);
  1348. if($totalData > 0){
  1349. $dataconversionrationtotal = ($totalDatasales/$totalData);
  1350. } else {
  1351. $dataconversionrationtotal = 0;
  1352. }
  1353. //echo "insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conatctable%','".@$contactperc."%',".@$contactpervalu.")"; die;
  1354. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('TotalData','".@$totalData."',".@$totalsourcewise.")");
  1355. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Sale','".@$totalDatasales."',".@$totalsourcewisesales.")");
  1356. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conatctabledata','".@$totalDatacontactable."',".@$totalcontactable.")");
  1357. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conatctable%','".@$contactperc."%',".@$contactpervalu.")");
  1358. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Datacontribution%','".@$Datacontributionprec."%',".@$datacontpervalu.")");
  1359. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conversion%','".@$dataconversionrationtotal."%',".@$conversionpercentagevalu.")");
  1360. // $tableres ="create table IF NOT EXISTS ".$table." as select leadSourceCode,leadSourceTitle from leadSourceMaster";
  1361. //$esx = mysql_query($tableres) or die(mysql_error());
  1362. $this->actiondatamis_download($start);
  1363. }
  1364. public function actiondatamis(){
  1365. ini_set('max_input_time', 19200);
  1366. ini_set('max_execution_time', 19200);
  1367. $host = '10.216.6.59'; // MYSQL database host adress
  1368. $db = 'lms'; // MYSQL database name
  1369. $user = 'root'; // Mysql Datbase user
  1370. $pass = '0kwp6aNR'; // Mysql Datbase password
  1371. $link=mysql_connect($host,$user,$pass);
  1372. mysql_select_db($db,$link);
  1373. $table='report_datamis';
  1374. $chktableExist = mysql_query('DROP TABLE IF EXISTS '.$table.' ') or die(mysql_error());
  1375. $parser = new CHtmlPurifier();
  1376. $afterMonth = $parser->purify(intval(@$_REQUEST['month']));
  1377. $afterYear = $parser->purify(intval(@$_REQUEST['year']));
  1378. if(isset($afterMonth) && !empty($afterMonth) && isset($afterYear) && !empty($afterYear)){
  1379. $start =mktime(0, 0, 0, $afterMonth, 1,$afterYear);
  1380. $end = mktime(23, 59, 0, $afterMonth, date('t', $start),$afterYear);
  1381. } else {
  1382. $start = strtotime('first day of this month', time());
  1383. $end = strtotime('last day of this month', time());
  1384. }
  1385. mysql_query("UPDATE `leadSourceMaster` SET leadSourceTitleReport=REPLACE(REPLACE(REPLACE(leadSourceTitle,' ',''),'-','_'),'.','')");
  1386. $resnews = mysql_query("SELECT group_concat(CONCAT(`leadSourceTitleReport`)) as res FROM `leadSourceMaster`");
  1387. $netres = mysql_fetch_array($resnews);
  1388. $strg = $netres['res'];
  1389. $replacedstr = str_replace(',',' varchar(50) ,',$strg)." varchar(50)";
  1390. $createsql = "CREATE TABLE IF NOT EXISTS ".$table." (
  1391. ".$replacedstr."
  1392. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
  1393. ";
  1394. mysql_query($createsql) or die(mysql_error());
  1395. mysql_query("ALTER TABLE ".$table." ADD `AgentName` VARCHAR( 150 ) NOT NULL FIRST ,
  1396. ADD `Total` VARCHAR( 50 ) NOT NULL AFTER `AgentName`");
  1397. $sourcecode = mysql_query("select distinct leadSourceTitleReport as leadSourceTitle,leadsourceCode from leadSourceMaster group by leadSourceTitleReport");
  1398. $row=0;
  1399. $arraymerger = array();
  1400. // $start = strtotime('first day of this month', time());
  1401. // $end = strtotime('last day of this month', time());
  1402. $totalsourcewise = array();
  1403. $totalsourcewisesales = array();
  1404. $totalcontactable = array();
  1405. $conversionpercentage = array();
  1406. $salesIds = '7';
  1407. $contactableids = '7,8,9,37,38,11,12,13,14,15,16,17,22,23,24,25,26';
  1408. $noncontactableids = '39,40,27,28,29,30,33,42,43';
  1409. while ($row = mysql_fetch_array($sourcecode)){
  1410. //echo $row['leadsourceCode'];
  1411. $arraymerger[$row['leadsourceCode']] = $row['leadSourceTitle'] ;
  1412. //echo 'select SUM(CASE WHEN ws_agentId = "'.@$row['leadsourceCode'].'" THEN 1 ELSE 0 END) AS total from lead'; die;
  1413. $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');
  1414. $querressum = mysql_fetch_assoc($quersum);
  1415. $totalsourcewise[] = $querressum['total'];
  1416. $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');
  1417. $querressumsales = mysql_fetch_assoc($quersumsales);
  1418. $totalsourcewisesales[] = $querressumsales['total'];
  1419. $conversionpercentage[$querressumsales['total']] = $querressum['total'];
  1420. $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');
  1421. $querressumcontactable = mysql_fetch_assoc($quersumcontactable);
  1422. $totalcontactable[] = $querressumcontactable['total'];
  1423. $row++; }
  1424. $keys = (implode(",",array_keys($arraymerger)));
  1425. $values = (implode(",",array_values($arraymerger)));
  1426. $q="replace into ".$table." (AgentName,".$values.") values ('AgentCode',".$keys.")";
  1427. mysql_query($q) or die(mysql_error());
  1428. // $maxDays=date('t');
  1429. $maxDays=date('d');
  1430. $totalData = 0;
  1431. $totalDatasales = 0;
  1432. $totalDatacontactable = 0;
  1433. for($y=1;$y<=$maxDays;$y++) {
  1434. $date = $y.date('/m/Y');
  1435. $explodedDate = explode('/',$date);
  1436. $time = strtotime($explodedDate[0]."-".$explodedDate[1]."-".$explodedDate[2]);
  1437. $timePm = strtotime($explodedDate[0]."-".$explodedDate[1]."-".$explodedDate[2])+86399;
  1438. $totalcountcode = array();
  1439. $totalcountsales = array();
  1440. $totalcountcontact = array();
  1441. $totalcountcoderes=0;
  1442. foreach($arraymerger as $key=>$values1){
  1443. $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.'"');
  1444. $querres = mysql_fetch_assoc($quer);
  1445. $totalcountcode[] = $querres['total'];
  1446. $totalcountcoderes =$querres['total'];
  1447. $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 ');
  1448. $salesqueryres = mysql_fetch_array($salesquery);
  1449. $totalcountsales[] = $salesqueryres['total'];
  1450. $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 ');
  1451. $contactqueryres = mysql_fetch_array($contactquery);
  1452. $totalcountcontact[] = $contactqueryres['total'];
  1453. }
  1454. $totalsumres = array_sum($totalcountcode);
  1455. $totalsumresales = array_sum($totalcountsales);
  1456. $totalcountcontact = array_sum($totalcountcontact);
  1457. $implodedcountcode = implode(",",$totalcountcode);
  1458. $totalData = $totalData+intval($totalsumres);
  1459. $totalDatasales = $totalDatasales+intval($totalsumresales);
  1460. $totalDatacontactable = $totalDatacontactable+intval($totalcountcontact);
  1461. intval($totalcountcoderes);
  1462. $totalsumsales = array_sum($totalcountsales);
  1463. //print_r($totalcountsales);
  1464. $datequery = "insert into ".$table."(`AgentName`,`Total`,".$values.") values('".$y.date('/M/Y')."',".$totalsumres.",".$implodedcountcode.")";
  1465. mysql_query($datequery);
  1466. }
  1467. $contactper = $totalcontactable;
  1468. $datacontper = $totalsourcewise;
  1469. $datacontpertest = $totalsourcewisesales;
  1470. $totalsourcewise = implode(",",$totalsourcewise);
  1471. $totalsourcewisesales = implode(",",$totalsourcewisesales);
  1472. $totalcontactable = implode(",",$totalcontactable);
  1473. if(@$totalDatacontactable > 0){
  1474. //$contactperc = ($totalDatacontactable*100)/$totalData;
  1475. $contactperc = ($totalDatasales*100)/$totalData;
  1476. } else {
  1477. $contactperc = '0';
  1478. }
  1479. $contactpervalu =array();
  1480. foreach($contactper as $key2=>$value2){
  1481. if($datacontper[$key2] > 0){
  1482. $contactpervalu[] = '"'.($value2*100)/$datacontper[$key2].'%"';
  1483. } else {
  1484. $contactpervalu[] = "'0%'";
  1485. }
  1486. // $contactpervalu[] = '"'.($value2*100)/$totalDatacontactable.'%"';
  1487. }
  1488. $contactpervalu = implode(",",$contactpervalu);
  1489. if(@$totalData > 0){
  1490. $Datacontributionprec = '100';
  1491. } else {
  1492. $Datacontributionprec = '0';
  1493. }
  1494. $datacontpervalu =array();
  1495. foreach($datacontper as $key4=>$value4){
  1496. if($totalData > 0){
  1497. $datacontpervalu[] = '"'.($value4*100)/$totalData.'%"';
  1498. } else {
  1499. $datacontpervalu[] = "'0%'";
  1500. }
  1501. }
  1502. $datacontpervalu = implode(",",$datacontpervalu);
  1503. $conversionPerkeys = array_keys($conversionpercentage);
  1504. $conversionPervalue = array_values($conversionpercentage);
  1505. $conversionnetres = array();
  1506. for($r=0;$r<count($datacontper);$r++){
  1507. if($datacontper[$r] > 0){
  1508. $conversionnetres[$r] = ($datacontpertest[$r]/$datacontper[$r]).'%"';
  1509. } else {
  1510. $conversionnetres[$r] = "'0%'";
  1511. }
  1512. }
  1513. $conversionpercentagevalu = implode(",",$conversionnetres);
  1514. if($totalData > 0){
  1515. $dataconversionrationtotal = ($totalDatasales/$totalData);
  1516. } else {
  1517. $dataconversionrationtotal = 0;
  1518. }
  1519. //echo "insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conatctable%','".@$contactperc."%',".@$contactpervalu.")"; die;
  1520. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('TotalData','".@$totalData."',".@$totalsourcewise.")");
  1521. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Sale','".@$totalDatasales."',".@$totalsourcewisesales.")");
  1522. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conatctabledata','".@$totalDatacontactable."',".@$totalcontactable.")");
  1523. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conatctable%','".@$contactperc."%',".@$contactpervalu.")");
  1524. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Datacontribution%','".@$Datacontributionprec."%',".@$datacontpervalu.")");
  1525. mysql_query("insert into ".$table."(`AgentName`,`Total`,".@$values.") values('Conversion%','".@$dataconversionrationtotal."%',".@$conversionpercentagevalu.")");
  1526. // $tableres ="create table IF NOT EXISTS ".$table." as select leadSourceCode,leadSourceTitle from leadSourceMaster";
  1527. //$esx = mysql_query($tableres) or die(mysql_error());
  1528. $this->actiondatamis_download($start);
  1529. }
  1530. public function actiondatamis_download($start){
  1531. ini_set('max_input_time', 300);
  1532. ini_set('max_execution_time', 300);
  1533. $date = date('d_M_Y').'_';
  1534. $host = '10.216.6.59'; // MYSQL database host adress
  1535. $db = 'lms'; // MYSQL database name
  1536. $user = 'root'; // Mysql Datbase user
  1537. $pass = '0kwp6aNR'; // Mysql Datbase password
  1538. $link=mysql_connect($host,$user,$pass);
  1539. mysql_select_db($db,$link);
  1540. $table='report_datamis';
  1541. $filename = "filesystem/".$date.$table.'.csv';
  1542. $csv_terminated = "\n";
  1543. $csv_separator = ",";
  1544. $csv_enclosed = '"';
  1545. $csv_escaped = "\\";
  1546. $time = time();
  1547. mysql_query("insert into report_info (id,type,filename,createdOn,createdBy,updatedOn,updatedBy) values('','datadumpmis','".@$filename."','".@$time."','".@$_SESSION['id']."','".@$time."','".@$_SESSION['id']."')");
  1548. $sql_query = "select * from ".$table."";
  1549. // Gets the data from the database
  1550. $result = mysql_query($sql_query);
  1551. $fields_cnt = mysql_num_fields($result);
  1552. $schema_insert = '';
  1553. for ($i = 0; $i < $fields_cnt; $i++)
  1554. {
  1555. $l = $csv_enclosed . str_replace($csv_enclosed, $csv_escaped . $csv_enclosed,
  1556. stripslashes(mysql_field_name($result, $i))) . $csv_enclosed;
  1557. $schema_insert .= $l;
  1558. $schema_insert .= $csv_separator;
  1559. } // end for
  1560. $out = trim(substr($schema_insert, 0, -1));
  1561. $out .= $csv_terminated;
  1562. // Format the data
  1563. while ($row = mysql_fetch_array($result))
  1564. {
  1565. $schema_insert = '';
  1566. for ($j = 0; $j < $fields_cnt; $j++)
  1567. {
  1568. if ($row[$j] == '0' || $row[$j] != '')
  1569. {
  1570. if ($csv_enclosed == '')
  1571. {
  1572. $schema_insert .= $row[$j];
  1573. } else
  1574. {
  1575. $schema_insert .= $csv_enclosed .
  1576. str_replace($csv_enclosed, $csv_escaped . $csv_enclosed, $row[$j]) . $csv_enclosed;
  1577. }
  1578. } else
  1579. {
  1580. $schema_insert .= '';
  1581. }
  1582. if ($j < $fields_cnt - 1)
  1583. {
  1584. $schema_insert .= $csv_separator;
  1585. }
  1586. } // end for
  1587. $out .= $schema_insert;
  1588. $out .= $csv_terminated;
  1589. } // end while
  1590. $fd = fopen($filename, "w");
  1591. fputs($fd, $out);
  1592. fclose($fd);
  1593. echo "success";
  1594. //header("Content-type: text/csv");
  1595. //header("Content-type: application/csv");
  1596. //echo $out;
  1597. exit;
  1598. }
  1599. public function actiondownloadallreports(){
  1600. $this->render('downloadallreports');
  1601. }
  1602. }
  1603. ?>