PageRenderTime 90ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/lms_debug/protected/controllers/LeadsController_11Jan15.php

https://gitlab.com/badelal143/lms_debug
PHP | 4481 lines | 3520 code | 597 blank | 364 comment | 665 complexity | 1a97629889fcdcdb6295c2273f98b269 MD5 | raw file
Possible License(s): LGPL-2.1, LGPL-3.0, LGPL-2.0
  1. <?php
  2. class LeadsController extends BaseController
  3. {
  4. const SHARED_TITLE = "Admin Panel";
  5. /**
  6. * Declares class-based actions.
  7. */
  8. public function filters()
  9. {
  10. return array( 'accessControl',array(
  11. 'CHttpCacheFilter + view',
  12. 'cacheControl' => " max-age=604800, must-revalidate",
  13. ) ); // perform access control for CRUD operations
  14. }
  15. public function actions()
  16. {
  17. return array(
  18. // captcha action renders the CAPTCHA image displayed on the contact page
  19. 'captcha'=>
  20. array(
  21. 'class'=>'CCaptchaAction',
  22. 'backColor'=>0xFFFFFF,
  23. ),
  24. // page action renders "static" pages stored under 'protected/views/site/pages'
  25. // They can be accessed via: index.php?r=site/page&view=FileName
  26. 'page'=>array(
  27. 'class'=>'CViewAction',
  28. ),
  29. );
  30. }
  31. /**
  32. * This is the 'roles' action that is invoked
  33. * when an action is not explicitly requested by users.
  34. */
  35. public function actionlead_welcome()
  36. {
  37. $model = new WelcomeMaster();
  38. $model = WelcomeMaster::model()->find("moduleId = '1' ");
  39. $this->render('lead_welcome',array('model'=>$model));
  40. }
  41. /**
  42. * This is the 'roles' action that is invoked
  43. * when an action is not explicitly requested by users.
  44. */
  45. public function actionlead_list()
  46. {
  47. $this->render('lead_list');
  48. }
  49. /**
  50. * This is the 'lead_list_allocator' action that is invoked
  51. * when an action is not explicitly requested by users.
  52. */
  53. public function actionlead_list_allocator()
  54. {
  55. // renders the view file 'protected/views/site/index.php'
  56. // using the default layout 'protected/views/layouts/main.php'
  57. $this->render('lead_list_allocator');
  58. }
  59. /**
  60. * This is the 'lead_list_allocator' action that is invoked
  61. * when an action is not explicitly requested by users.
  62. */
  63. public function actionfollowup_lead_list()
  64. {
  65. $today12PM = mktime(0,0,0,date("m"),date("d"),date("Y"));
  66. $relationManager = $_SESSION['relationalManager'];
  67. $managerMemberId = implode(",",array_unique(@$relationManager));
  68. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  69. $querycondition = ' startDate = "'.@$today12PM.'" and status="Pending" ';
  70. } else {
  71. $querycondition = " startDate = '".@$today12PM."' AND status = 'Pending' AND userId IN (".@$managerMemberId.") ";
  72. }
  73. //$modelLead = LeadFollowup::model()->findAll(" $querycondition ");
  74. $this->render('followup_lead_list');
  75. }
  76. public function actionfollowup_overall_lead_list()
  77. {
  78. $relationManager = $_SESSION['relationalManager'];
  79. $managerMemberId = implode(",",array_unique(@$relationManager));
  80. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  81. $querycondition = ' status="Pending" ';
  82. } else {
  83. $querycondition = " status = 'Pending' AND userId IN (".@$managerMemberId.") ";
  84. }
  85. //$modelLead = LeadFollowup::model()->findAll(" $querycondition ");
  86. $this->render('followup_overall_lead_list');
  87. }
  88. /**
  89. * This is the 'lead_list_allocator' action that is invoked
  90. * when an action is not explicitly requested by users.
  91. */
  92. public function actionlead_list_tc()
  93. {
  94. // renders the view file 'protected/views/site/index.php'
  95. // using the default layout 'protected/views/layouts/main.php'
  96. $this->render('lead_list_tc');
  97. }
  98. /**
  99. * This is the 'lead_list_allocator' action that is invoked
  100. * when an action is not explicitly requested by users.
  101. */
  102. public function actionjunk_lead_list()
  103. {
  104. //$modelLead = Lead::model()->findAll(" leadStatusId = '36' ");
  105. $this->render('junk_lead_list');
  106. }
  107. /**
  108. * This is the 'lead_list_allocator' action that is invoked
  109. * when an action is not explicitly requested by users.
  110. */
  111. public function actionduplicate_lead_list()
  112. {
  113. //$modelLead = Lead::model()->findAll(" leadStatusId = '10' ");
  114. $this->render('duplicate_lead_list');
  115. }
  116. public function actionclose_lead_list()
  117. {
  118. //$modelLead = Lead::model()->findAll(" leadStatusId = '7' ");
  119. $this->render('close_lead_list');
  120. }
  121. /**
  122. * This is the 'lead_list_allocator' action that is invoked
  123. * when an action is not explicitly requested by users.
  124. */
  125. public function actionallocated_lead_list()
  126. {
  127. $relationManager = $_SESSION['relationalManager'];
  128. $managerMemberId = implode(",",array_unique(@$relationManager));
  129. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  130. $querycondition = " currentAllocatedId>0 AND isRead = 'yes'";
  131. } else {
  132. $querycondition = " currentAllocatedId >0 AND isRead = 'yes' AND currentAllocatedId IN (".@$managerMemberId.") ";
  133. }
  134. //$modelLead = Lead::model()->findAll(" $querycondition ");
  135. $this->render('allocated_lead_list');
  136. }
  137. /**
  138. * This is the 'lead_list_allocator' action that is invoked
  139. * when an action is not explicitly requested by users.
  140. */
  141. public function actionleads_details()
  142. {
  143. // renders the view file 'protected/views/site/index.php'
  144. // using the default layout 'protected/views/layouts/main.php'
  145. //for follow up
  146. $parser = new CHtmlPurifier();
  147. if (isset($_POST['LeadFollowup']))
  148. {
  149. if (isset($_POST['LeadFollowup']['chkActionValid']) && @$_POST['LeadFollowup']['chkActionValid'] == 1)
  150. {
  151. $res = $this->actionlead_followup(@$_POST['LeadFollowup'], $parser->purify(intval(@$_POST['Lead']['leadStatusId'])));
  152. $decodeRes = json_decode($res);
  153. if (@$decodeRes->status == 'success')
  154. {
  155. echo CJSON::encode(array(
  156. 'status' => 'success'
  157. ));
  158. }
  159. else
  160. {
  161. echo $res;
  162. }
  163. }
  164. }
  165. $leadFollDesc = @$_POST['LeadFollowup']['description'];
  166. // end of for follow ups
  167. $leadId = $parser->purify(intval(@$_GET['leadId']));
  168. $actionId = $parser->purify(intval(@$_REQUEST['actionId']));
  169. $actionmodel = LeadFollowup::model()->findByPk($actionId);
  170. $model = new Lead();
  171. $this->performAjaxValidation($model);
  172. $model->scenario = 'Lead';
  173. $managerMemberId = implode(",", $_SESSION['relationalManager']);
  174. $chkAllocatedLeads = $managerMemberId ? Lead::model()->findAll(array("select" => " leadId", "condition" => " leadStatusId != '26' AND leadStatusId != '25' AND currentAllocatedId IN (" . @$managerMemberId . ") ")) : '0';
  175. /* $allocatedArr = array();
  176. foreach ($chkAllocatedLeads as $key => $value)
  177. {
  178. $allocatedArr[] = $chkAllocatedLeads[$key]->leadId;
  179. }
  180. //print_r($allocatedArr);
  181. //die;
  182. if(Yii::app()->session->get('isAllocator')!='yes' and Yii::app()->session->get('type')!='superadmin'){
  183. if(!in_array($leadId,$allocatedArr)){
  184. $this->redirect(array('leads/lead_list'));
  185. }
  186. } */
  187. if (!empty($leadId))
  188. {
  189. $model = Lead::model()->findByPk($leadId);
  190. $chkrecentlyViewed = recentlyViewed::model()->findByAttributes(array('leadId' => $leadId, 'userId' => Yii::app()->session->get('id')));
  191. if (count($chkrecentlyViewed) == 0)
  192. {
  193. $recentlyViewed = new recentlyViewed();
  194. $recentlyViewed->setAttributes(array(
  195. 'userId' => Yii::app()->session->get('id'),
  196. 'leadId' => $leadId,
  197. 'moduleId' => 0,
  198. 'updatedOn' => $_SESSION['id'],
  199. 'updatedBy' => $_SESSION['id'],
  200. ));
  201. $recentlyViewed->save(false);
  202. }
  203. }
  204. if (isset($_POST['Lead']))
  205. {
  206. if ($_POST['LeadFollowup']['startDate'] != '')
  207. {
  208. $finalLeadDesc = @$leadFollDesc;
  209. }
  210. else
  211. {
  212. $finalLeadDesc = @$_POST['Lead']['leadDescription'];
  213. }
  214. $model->setAttributes(array(
  215. 'updatedOn' => time(), //additional
  216. 'updatedBy' => $_SESSION['id'], //additional
  217. 'status' => 'Active', //additional //additional
  218. 'leadDescription' => @$finalLeadDesc, //additional //additional
  219. ));
  220. $prevLeadStatusId = $model->leadStatusId;
  221. $prevCurrentAllocatedId = $model->currentAllocatedId;
  222. foreach ($_POST['Lead'] as $name => $value)
  223. {
  224. if ($model->leadStatusId == '')
  225. {
  226. $model->leadStatusId = $model->leadStatusParentId;
  227. }
  228. if ($model->email == 'Email')
  229. {
  230. $model->email = '';
  231. }
  232. if ($model->name == 'Name')
  233. {
  234. $model->name = '';
  235. }
  236. if ($model->address == 'Address')
  237. {
  238. $model->address = '';
  239. }
  240. if ($model->ws_proposalid == 'Proposal No.')
  241. {
  242. $model->ws_proposalid = '';
  243. }
  244. if ($model->children == "Children (Less than 25 Yrs)")
  245. {
  246. $model->children = '';
  247. }
  248. if ($model->ageGroup == "Age of eldest member")
  249. {
  250. $model->ageGroup = '';
  251. }
  252. if ($model->leadDescription == "Lead Description")
  253. {
  254. $model->leadDescription = '';
  255. }
  256. if ($model->leadStatusId == '')
  257. {
  258. $model->leadStatusId = $prevLeadStatusId;
  259. }
  260. if (@$leadId != '' && $model->leadStatusId != '34' && @$model->leadStatusId != '35')
  261. {
  262. $model->isRead = 'yes';
  263. }
  264. if (is_array($value))
  265. {
  266. $value = '';
  267. }
  268. else
  269. {
  270. $value = $value;
  271. }
  272. $model->$name = $parser->purify($value);
  273. }
  274. //------------------------------------------------------
  275. $accesskeyYear = $currentYear = date('Y');
  276. $accesskeyMonth = date('m');
  277. if ($model->currentAllocatedDate)
  278. {
  279. $accesskeyYear = date('Y', $model->currentAllocatedDate);
  280. $accesskeyMonth = date('m', $model->currentAllocatedDate);
  281. }
  282. else
  283. {
  284. if ($model->updatedOn)
  285. {
  286. $accesskeyYear = date('Y', $model->updatedOn);
  287. $accesskeyMonth = date('m', $model->updatedOn);
  288. }
  289. }
  290. if ($currentYear != $accesskeyYear)
  291. {
  292. if (BaseController::getConfigurationValue('leadallcount'))
  293. ;
  294. {
  295. DashboardController::insertUserLeadAllCountRecord($accesskeyYear);
  296. }
  297. }
  298. $currentStatus = $_POST['Lead']['leadStatusId'];
  299. $updatedOn = time();
  300. $updatedBy = Yii::app()->session['id'];
  301. if (!$prevCurrentAllocatedId)
  302. {
  303. $prevCurrentAllocatedId = 1;
  304. }
  305. Yii::app()->db->createCommand('START TRANSACTION;')->execute();
  306. if ($currentStatus != $prevLeadStatusId && $currentStatus != '')
  307. {
  308. if (BaseController::getConfigurationValue('leadallcount'))
  309. {
  310. if (Yii::app()->session->get('type') != 'superadmin')
  311. {
  312. Yii::app()->db->createCommand("update leadallcount set count = count - 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  313. where userid = $prevCurrentAllocatedId and leadtype = $prevLeadStatusId
  314. and accesskey = '$accesskeyYear'")->execute();
  315. Yii::app()->db->createCommand("update leadallcount set count = count - 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  316. where userid = $prevCurrentAllocatedId and leadtype = $prevLeadStatusId
  317. and accesskey = '$accesskeyYear-$accesskeyMonth'")->execute();
  318. Yii::app()->db->createCommand("update leadallcount set count = count + 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  319. where userid = $updatedBy and leadtype = $currentStatus
  320. and accesskey = '$accesskeyYear'")->execute();
  321. Yii::app()->db->createCommand("update leadallcount set count = count + 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  322. where userid = $updatedBy and leadtype = $currentStatus
  323. and accesskey = '$accesskeyYear-$accesskeyMonth'")->execute();
  324. }
  325. Yii::app()->db->createCommand("update leadallcount set count = count - 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  326. where userid = 1 and leadtype = $prevLeadStatusId
  327. and accesskey = '$accesskeyYear'")->execute();
  328. Yii::app()->db->createCommand("update leadallcount set count = count - 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  329. where userid = 1 and leadtype = $prevLeadStatusId
  330. and accesskey = '$accesskeyYear-$accesskeyMonth'")->execute();
  331. Yii::app()->db->createCommand("update leadallcount set count = count + 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  332. where userid = 1 and leadtype = $currentStatus
  333. and accesskey = '$accesskeyYear'")->execute();
  334. Yii::app()->db->createCommand("update leadallcount set count = count + 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  335. where userid = 1 and leadtype = $currentStatus
  336. and accesskey = '$accesskeyYear-$accesskeyMonth'")->execute();
  337. }
  338. Yii::app()->db->createCommand('COMMIT;')->execute();
  339. }
  340. else
  341. {
  342. Yii::app()->db->createCommand('ROLLBACK;')->execute();
  343. }
  344. // Added by shakti upto here.
  345. if ($model->leadStatusParentId == '1')
  346. {
  347. $model->salesClosedUpdatedOn = time();
  348. }
  349. $fetchAgentDetails = LeadSourceMaster::model()->findByPk($model->leadSourceId);
  350. $model->agentId = @$fetchAgentDetails->leadSourceCode;
  351. $model->ws_agentid = @$fetchAgentDetails->leadSourceCode;
  352. if (@$leadId != '' && $model->leadStatusId != '34')
  353. {
  354. $update = Yii::app()->db->createCommand("update `lead` set `isRead`='yes' where `leadId`='$leadId' and currentAllocatedId > 0")->query();
  355. }
  356. $chkStatusMandatoryOrNot = leadStatus::model()->findByAttributes(array('leadStatusId' => $model->leadStatusId));
  357. if ($model->leadStatusId == '1')
  358. {
  359. $model->scenario = 'salesclosed';
  360. }
  361. if (count($chkStatusMandatoryOrNot) > 0)
  362. {
  363. $condMandatory = $chkStatusMandatoryOrNot['compulsary'];
  364. if ($condMandatory == 'No')
  365. {
  366. if ($model->validate(array('mobile')))
  367. {
  368. if (@$_POST['Lead']['emailOptOut'] == 'on')
  369. {
  370. $model->emailOptOut = 'Y';
  371. }
  372. else
  373. {
  374. $model->emailOptOut = 'N';
  375. }
  376. if (@$_POST['Lead']['mobileOptOut'] == 'on')
  377. {
  378. $model->mobileOptOut = 'Y';
  379. }
  380. else
  381. {
  382. $model->mobileOptOut = 'N';
  383. }
  384. if (@$_POST['Lead']['isJunk'] == 'on')
  385. {
  386. $model->isJunk = 'yes';
  387. }
  388. else
  389. {
  390. $model->isJunk = 'no';
  391. }
  392. if (@$_POST['Lead']['isDuplicate'] == 'on')
  393. {
  394. $model->isDuplicate = 'yes';
  395. }
  396. else
  397. {
  398. $model->isDuplicate = 'no';
  399. }
  400. if (@$_POST['Lead']['status'] == 'on')
  401. {
  402. $model->status = 'Close';
  403. }
  404. else
  405. {
  406. $model->status = 'Active';
  407. }
  408. $modelHistory = new LeadHistory();
  409. $modelHistory->scenario = 'LeadHistory';
  410. $modelHistory->setAttributes(array(
  411. 'leadId' => @$leadId, //additional data you want to insert
  412. 'updatedOn' => time(), //additional
  413. 'updatedBy' => $_SESSION['id'], //additional
  414. 'status' => 'Active', //additional
  415. 'leadDescription' => @$finalLeadDesc,
  416. ));
  417. foreach ($_POST['Lead'] as $name1 => $value1)
  418. {
  419. if ($modelHistory->leadStatusId == '')
  420. {
  421. $modelHistory->leadStatusId = $modelHistory->leadStatusParentId;
  422. }
  423. if (@$_POST['LeadFollowup']['description'] == 'Description')
  424. {
  425. $activitydesc = '';
  426. }
  427. else
  428. {
  429. $activitydesc = @$_POST['LeadFollowup']['description'];
  430. }
  431. $modelHistory->activityDescription = @$activitydesc;
  432. if ($model->leadStatusId == '')
  433. {
  434. $model->leadStatusId = 2;
  435. }
  436. if ($modelHistory->email == 'Email')
  437. {
  438. $modelHistory->email = '';
  439. }
  440. if ($modelHistory->name == 'Name')
  441. {
  442. $modelHistory->name = '';
  443. }
  444. if ($modelHistory->address == 'Address')
  445. {
  446. $modelHistory->address = '';
  447. }
  448. if ($modelHistory->leadDescription == "Lead Description")
  449. {
  450. $modelHistory->leadDescription = '';
  451. }
  452. if ($modelHistory->children == "Children (Less than 25 Yrs)")
  453. {
  454. $modelHistory->children = '';
  455. }
  456. if ($modelHistory->ageGroup == "Age of eldest member")
  457. {
  458. $modelHistory->ageGroup = '';
  459. }
  460. if (is_array($value1))
  461. {
  462. $value1 = '';
  463. }
  464. else
  465. {
  466. $value1 = $value1;
  467. }
  468. $modelHistory->$name1 = $parser->purify($value1);
  469. }
  470. $model->save(false);
  471. $modelHistory->save();
  472. CJSON::encode(array(
  473. 'status' => 'success'
  474. ));
  475. Yii::app()->end();
  476. }
  477. }
  478. }
  479. $model->save();
  480. if ($model->validate())
  481. {
  482. if (@$_POST['Lead']['emailOptOut'] == 'on')
  483. {
  484. $model->emailOptOut = 'Y';
  485. }
  486. else
  487. {
  488. $model->emailOptOut = 'N';
  489. }
  490. if (@$_POST['Lead']['mobileOptOut'] == 'on')
  491. {
  492. $model->mobileOptOut = 'Y';
  493. }
  494. else
  495. {
  496. $model->mobileOptOut = 'N';
  497. }
  498. if (@$_POST['Lead']['isJunk'] == 'on')
  499. {
  500. $model->isJunk = 'yes';
  501. }
  502. else
  503. {
  504. $model->isJunk = 'no';
  505. }
  506. if (@$_POST['Lead']['isDuplicate'] == 'on')
  507. {
  508. $model->isDuplicate = 'yes';
  509. }
  510. else
  511. {
  512. $model->isDuplicate = 'no';
  513. }
  514. if (@$_POST['Lead']['status'] == 'on')
  515. {
  516. $model->status = 'Close';
  517. }
  518. else
  519. {
  520. $model->status = 'Active';
  521. }
  522. $modelHistory = new LeadHistory();
  523. $modelHistory->scenario = 'LeadHistory';
  524. $modelHistory->setAttributes(array(
  525. 'leadId' => @$leadId, //additional data you want to insert
  526. 'updatedOn' => time(), //additional
  527. 'updatedBy' => $_SESSION['id'], //additional
  528. 'status' => 'Active', //additional
  529. 'leadDescription' => @$finalLeadDesc,
  530. ));
  531. foreach ($_POST['Lead'] as $name1 => $value1)
  532. {
  533. if ($modelHistory->leadStatusId == '')
  534. {
  535. $modelHistory->leadStatusId = $modelHistory->leadStatusParentId;
  536. }
  537. $modelHistory->activityDescription = @$_POST['LeadFollowup']['description'];
  538. if ($model->leadStatusId == '')
  539. {
  540. $model->leadStatusId = 2;
  541. }
  542. if (is_array($value1))
  543. {
  544. $value1 = '';
  545. }
  546. else
  547. {
  548. $value1 = $value1;
  549. }
  550. $modelHistory->$name1 = $parser->purify($value1);
  551. }
  552. $modelHistory->save();
  553. echo CJSON::encode(array(
  554. 'status' => 'success'
  555. ));
  556. Yii::app()->end();
  557. //Yii::app()->end();
  558. //die;
  559. //$this->redirect(array('leads/leads_details'));
  560. }
  561. else
  562. {
  563. @$error = CActiveForm::validate(@$model);
  564. if ($error != '[]')
  565. echo @$error;
  566. Yii::app()->end();
  567. //$this->render('leads_details',array('model'=>$model));
  568. }
  569. } else
  570. {
  571. $this->render('leads_details', array('model' => @$model, 'actionmodel' => @$actionmodel, 'quotesmobile' => @$model->mobile));
  572. }
  573. }
  574. protected function performAjaxValidation($models)
  575. {
  576. if(isset($_POST['ajax']) && $_POST['ajax']==='user-form')
  577. {
  578. echo CActiveForm::validate($models);
  579. Yii::app()->end();
  580. }
  581. }
  582. /**
  583. * This is the 'lead_list_allocator' action that is invoked
  584. * when an action is not explicitly requested by users.
  585. */
  586. public function actionlead_followup()
  587. {
  588. $actionId = @$_REQUEST['actionId'];
  589. $model = new LeadFollowup();
  590. $model->scenario = 'LeadFollowup';
  591. if(isset($actionId) && !empty($actionId)){
  592. $model=LeadFollowup::model()->findByPk($actionId);
  593. } else {
  594. }
  595. if(isset($_POST['LeadFollowup']['actionType']) && $_POST['LeadFollowup']['actionType']=='Task'){
  596. $model->scenario = 'LeadFollowupTask';
  597. }if(isset($_POST['LeadFollowup']['actionType']) && $_POST['LeadFollowup']['actionType']=='Follow Up'){
  598. $model->scenario = 'LeadFollowup';
  599. }if(isset($_POST['LeadFollowup']['actionType']) && $_POST['LeadFollowup']['actionType']=='Meeting'){
  600. $model->scenario = 'LeadFollowup';
  601. }if(isset($_POST['LeadFollowup']['actionType']) && $_POST['LeadFollowup']['actionType']=='Notes'){
  602. $model->scenario = 'LeadFollowupNotes';
  603. }
  604. $parser = new CHtmlPurifier();
  605. $this->performAjaxValidation($model);
  606. if(isset($_POST['LeadFollowup']))
  607. {
  608. $userId = $_POST['LeadFollowup']['userId'];
  609. $followupstartdatewithtime = strtotime(@$_POST['LeadFollowup']['startDate'])+(@$_POST['LeadFollowup']['hour']*60*60)+(@$_POST['LeadFollowup']['minutes']*60);
  610. $model->setAttributes(array(
  611. 'createdOn' => time(), //additional data you want to insert
  612. 'updatedOn' => time(), //additional
  613. 'updatedBy' => @$userId, //additional
  614. 'createdBy' => @$userId, //additional
  615. 'status' => 'Pending', //additional
  616. ));
  617. foreach($_POST['LeadFollowup'] as $name=>$value)
  618. {
  619. if(is_array($value)){
  620. $value = '';
  621. } else {
  622. $value = $value;
  623. }
  624. $model->$name=$parser->purify($value);
  625. }
  626. $model->leadStatusId=@$_POST['Lead']['leadStatusId'];;
  627. $model->startDateWithTime=@$followupstartdatewithtime;
  628. if(@$_POST['LeadFollowup']['actionType']=='Notes') {
  629. $prefix=substr(time(),0,5);
  630. $folder = 'siteupload/';
  631. $model->notesFile=CUploadedFile::getInstance($model,'notesFile');
  632. if($model->notesFile !='')
  633. $model->notesFile->saveAs($folder.$prefix.$model->notesFile);
  634. $model->notesFile=$prefix.CUploadedFile::getInstance($model,'notesFile');
  635. }
  636. if(@$_POST['LeadFollowup']['startDate']!='') {
  637. $startDateVal = strtotime($_POST['LeadFollowup']['startDate']);
  638. $model->startDate=@$startDateVal;
  639. }
  640. if(@$_POST['LeadFollowup']['taskDueDate']!='') {
  641. $taskDueDateVal = strtotime($_POST['LeadFollowup']['taskDueDate']);
  642. $model->taskDueDate=@$taskDueDateVal;
  643. }
  644. if(@$_POST['LeadFollowup']['taskCompleted']!='') {
  645. $model->taskCompleted='yes';
  646. }
  647. if($model->validate()){
  648. $checkForSameDateExistsOrNot=LeadFollowup::model()->findAll(" leadId='".@$_POST['LeadFollowup']['leadId']."' and startDate <= '".$model->startDate."' and userId = '".@$userId."' and createdBy = '".@$userId."' ");
  649. if(count(@$checkForSameDateExistsOrNot) > 0){
  650. $update = Yii::app()->db->createCommand("UPDATE leadFollowup SET taskCompleted = 'yes',status = 'Completed' WHERE startDate <= '".$model->startDate."' and userId = '".@$userId."' and createdBy = '".@$userId."' and leadId='".@$_POST['LeadFollowup']['leadId']."' ")->execute();
  651. }
  652. $model->save();
  653. $leadId = $_POST['LeadFollowup']['leadId'];
  654. return CJSON::encode(array(
  655. 'status'=>'success'
  656. ));
  657. Yii::app()->end();
  658. } else {
  659. $error = CActiveForm::validate($model);
  660. if($error!='[]')
  661. return $error;
  662. Yii::app()->end();
  663. }
  664. //$this->redirect(array('leads/leads_details', 'leadId'=>@$leadId));
  665. }
  666. $this->redirect(array('leads/lead_list'));
  667. }
  668. /**
  669. * This is the 'lead_list_allocator' action that is invoked
  670. * when an action is not explicitly requested by users.
  671. */
  672. public function actionlead_followupcalender()
  673. {
  674. $actionId = @$_REQUEST['actionId'];
  675. $model = new LeadFollowup();
  676. $model->scenario = 'LeadFollowup';
  677. if(isset($actionId) && !empty($actionId)){
  678. $model=LeadFollowup::model()->findByPk($actionId);
  679. } else {
  680. }
  681. if(isset($_POST['LeadFollowup']['actionType']) && $_POST['LeadFollowup']['actionType']=='Task'){
  682. $model->scenario = 'LeadFollowupTask';
  683. }if(isset($_POST['LeadFollowup']['actionType']) && $_POST['LeadFollowup']['actionType']=='Follow Up'){
  684. $model->scenario = 'LeadFollowup';
  685. }if(isset($_POST['LeadFollowup']['actionType']) && $_POST['LeadFollowup']['actionType']=='Meeting'){
  686. $model->scenario = 'LeadFollowup';
  687. }if(isset($_POST['LeadFollowup']['actionType']) && $_POST['LeadFollowup']['actionType']=='Notes'){
  688. $model->scenario = 'LeadFollowupNotes';
  689. }
  690. $this->performAjaxValidation($model);
  691. if(isset($_POST['LeadFollowup']))
  692. {
  693. $userId = $_POST['LeadFollowup']['userId'];
  694. $model->setAttributes(array(
  695. 'createdOn' => time(), //additional data you want to insert
  696. 'updatedOn' => time(), //additional
  697. 'updatedBy' => @$userId, //additional
  698. 'createdBy' => @$userId, //additional
  699. 'status' => 'Pending', //additional
  700. ));
  701. foreach($_POST['LeadFollowup'] as $name=>$value)
  702. {
  703. $model->$name=$value;
  704. }
  705. $model->leadStatusId=@$_POST['Lead']['leadStatusId'];;
  706. if(@$_POST['LeadFollowup']['actionType']=='Notes') {
  707. $prefix=substr(time(),0,5);
  708. $folder = 'siteupload/';
  709. $model->notesFile=CUploadedFile::getInstance($model,'notesFile');
  710. if($model->notesFile !='')
  711. $model->notesFile->saveAs($folder.$prefix.$model->notesFile);
  712. $model->notesFile=$prefix.CUploadedFile::getInstance($model,'notesFile');
  713. }
  714. if(@$_POST['LeadFollowup']['startDate']!='') {
  715. $startDateVal = strtotime($_POST['LeadFollowup']['startDate']);
  716. $model->startDate=@$startDateVal;
  717. }
  718. if(@$_POST['LeadFollowup']['taskDueDate']!='') {
  719. $taskDueDateVal = strtotime($_POST['LeadFollowup']['taskDueDate']);
  720. $model->taskDueDate=@$taskDueDateVal;
  721. }
  722. if(@$_POST['LeadFollowup']['taskCompleted']!='') {
  723. $model->taskCompleted='yes';
  724. }
  725. if($model->validate()){
  726. $model->save();
  727. $leadId = $_POST['LeadFollowup']['leadId'];
  728. echo CJSON::encode(array(
  729. 'status'=>'success'
  730. ));
  731. Yii::app()->end();
  732. } else {
  733. $error = CActiveForm::validate($model);
  734. if($error!='[]')
  735. return $error;
  736. Yii::app()->end();
  737. }
  738. //$this->redirect(array('leads/leads_details', 'leadId'=>@$leadId));
  739. }
  740. $this->redirect(array('leads/lead_list'));
  741. }
  742. public function actionlead_contacts()
  743. {
  744. // renders the view file 'protected/views/site/index.php'
  745. // using the default layout 'protected/views/layouts/main.php'
  746. $model = new LeadContacts();
  747. $model->scenario = 'LeadContacts';
  748. $this->performAjaxValidation($model);
  749. if(!empty($_GET['contactId']))
  750. {
  751. $leadContactId=$_GET['leadContactId'];
  752. $model=LeadContacts::model()->findByPk($leadContactId);
  753. }
  754. if(!empty($_POST['LeadContacts']['leadContactId']))
  755. {
  756. $leadContactId=$_POST['LeadContacts']['leadContactId'];
  757. $model=LeadContacts::model()->findByPk($leadContactId);
  758. }
  759. if(isset($_POST['LeadContacts']))
  760. {
  761. $userId = $_POST['LeadContacts']['userId'];
  762. $leadId = $_POST['LeadContacts']['leadId'];
  763. $model->setAttributes(array(
  764. 'createdOn' => time(), //additional data you want to insert
  765. 'updatedOn' => time(), //additional
  766. 'updatedBy' => @$userId, //additional
  767. 'createdBy' => @$userId, //additional
  768. 'status' => 'Active', //additional
  769. ));
  770. foreach($_POST['LeadContacts'] as $name=>$value)
  771. {
  772. $model->$name=$value;
  773. }
  774. if($model->validate()){
  775. $model->save();
  776. echo CJSON::encode(array(
  777. 'status'=>'success'
  778. ));
  779. Yii::app()->end();
  780. } else {
  781. $error = CActiveForm::validate($model);
  782. if($error!='[]')
  783. echo $error;
  784. Yii::app()->end();
  785. }
  786. //$this->redirect(array('leads/leads_details', 'leadId'=>@$leadId));
  787. }
  788. $this->redirect(array('leads/lead_list'));
  789. }
  790. public function actionChangeContactStatus()
  791. {
  792. $Id=$_REQUEST['contactId'];
  793. $leadId=$_REQUEST['leadId'];
  794. $status=$_REQUEST['status'];
  795. if(isset($status)&&($status=='Inactive')){
  796. $status="Active";
  797. } else {
  798. $status="Inactive";
  799. }
  800. if(!empty($Id))
  801. {
  802. $model=LeadContacts::model()->findByPk($Id);
  803. }
  804. else
  805. {
  806. $model = LeadContacts::model()->findAll();
  807. }
  808. $model->status=$status;
  809. $model->save();
  810. $this->redirect(array('leads/leads_details', 'leadId'=>@$leadId));
  811. }
  812. /**
  813. * This is the 'roles' action that is invoked
  814. * when an action is not explicitly requested by users.
  815. */
  816. public function actioncreate_lead()
  817. {
  818. $model = new Lead();
  819. $model->scenario = 'Lead';
  820. if (!empty($_GET['leadId']))
  821. {
  822. $leadId = $_GET['leadId'];
  823. $model = Lead::model()->findByPk($leadId);
  824. $chkrecentlyViewed = recentlyViewed::model()->findByAttributes(array('leadId' => $leadId, 'userId' => Yii::app()->session->get('id')));
  825. if (count($chkrecentlyViewed) == 0)
  826. {
  827. $recentlyViewed = new recentlyViewed;
  828. $recentlyViewed->setAttributes(array(
  829. 'userId' => Yii::app()->session->get('id'),
  830. 'leadId' => $leadId,
  831. 'moduleId' => 0,
  832. 'createdOn' => time(),
  833. 'updatedOn' => time(),
  834. 'updatedBy' => Yii::app()->session->get('id'),
  835. 'createdBy' => Yii::app()->session->get('id'),
  836. ));
  837. $recentlyViewed->save(false);
  838. }
  839. }
  840. if (!empty($_POST['Lead']['leadId']))
  841. {
  842. $leadId = $_POST['Lead']['leadId'];
  843. $model = Lead::model()->findByPk($leadId);
  844. }
  845. if (isset($_POST['Lead']))
  846. {
  847. $model->setAttributes(array(
  848. 'createdOn' => time(), //additional data you want to insert
  849. 'updatedOn' => time(), //additional
  850. 'updatedBy' => Yii::app()->session->get('id'), //additional
  851. 'createdBy' => Yii::app()->session->get('id'),
  852. ));
  853. foreach ($_POST['Lead'] as $name => $value)
  854. {
  855. $model->$name = $value;
  856. if ($model->leadStatusId == '')
  857. {
  858. $model->leadStatusId = $model->leadStatusParentId;
  859. }
  860. if ($model->leadStatusId == '')
  861. {
  862. $model->leadStatusId = 34;
  863. }
  864. if ($model->mobile == 'Mobile*')
  865. {
  866. $model->mobile = '';
  867. }
  868. if ($model->email == 'Email')
  869. {
  870. $model->email = '';
  871. }
  872. if ($model->name == 'Name')
  873. {
  874. $model->name = '';
  875. }
  876. if ($model->address == 'Address')
  877. {
  878. $model->address = '';
  879. }
  880. if ($model->children == "Children (Less than 25 Yrs)")
  881. {
  882. $model->children = '';
  883. }
  884. if ($model->ageGroup == "Age of eldest member")
  885. {
  886. $model->ageGroup = '';
  887. }
  888. }
  889. if ($model->leadStatusParentId == '1')
  890. {
  891. $model->salesClosedUpdatedOn = time();
  892. }
  893. if ($model->leadSourceId == '' or empty($model->leadSourceId))
  894. {
  895. $model->leadSourceId = '2';
  896. }
  897. $fetchAgentDetails = LeadSourceMaster::model()->findByPk($model->leadSourceId);
  898. $model->agentId = @$fetchAgentDetails->leadSourceCode;
  899. $model->ws_agentid = @$fetchAgentDetails->leadSourceCode;
  900. if (Yii::app()->session->get('isAllocator') != 'yes' and Yii::app()->session->get('type') != 'superadmin')
  901. {
  902. @$model->leadStatusId = 35;
  903. @$model->currentAllocatedId = Yii::app()->session->get('id');
  904. }
  905. if (@$leadId != '' && $model->leadStatusId != '34')
  906. {
  907. $update = Yii::app()->db->createCommand("update `lead` set `isRead`='yes' where `leadId`='$leadId' and currentAllocatedId > 0")->query();
  908. }
  909. if (@$_POST['Lead']['emailOptOut'] == 'on')
  910. {
  911. $model->emailOptOut = 'Y';
  912. }
  913. else
  914. {
  915. $model->emailOptOut = 'N';
  916. }
  917. if (@$_POST['Lead']['mobileOptOut'] == 'on')
  918. {
  919. $model->mobileOptOut = 'Y';
  920. }
  921. else
  922. {
  923. $model->mobileOptOut = 'N';
  924. }
  925. if (@$_POST['Lead']['isJunk'] == 'on')
  926. {
  927. $model->isJunk = 'yes';
  928. }
  929. else
  930. {
  931. $model->isJunk = 'no';
  932. }
  933. if (@$_POST['Lead']['isDuplicate'] == 'on')
  934. {
  935. $model->isDuplicate = 'yes';
  936. }
  937. else
  938. {
  939. $model->isDuplicate = 'no';
  940. }
  941. if (@$_POST['Lead']['status'] == 'on')
  942. {
  943. $model->status = 'Close';
  944. }
  945. else
  946. {
  947. $model->status = 'Active';
  948. }
  949. $chkStatusMandatoryOrNot = leadStatus::model()->findByAttributes(array('leadStatusId' => $model->leadStatusId));
  950. if (count($chkStatusMandatoryOrNot) > 0)
  951. {
  952. $condMandatory = $chkStatusMandatoryOrNot['compulsary'];
  953. if ($condMandatory == 'No')
  954. {
  955. if ($model->validate(array('mobile')))
  956. {
  957. $mobileNumber = @$_POST['Lead']['mobile'];
  958. $checkJunkNumber = JunkNumbersMaster::model()->find('junkLeadNumber = "' . @$mobileNumber . '"');
  959. if (empty($checkJunkNumber))
  960. {
  961. $beforethreemonth = time() - 7776000;
  962. $checkDuplicateNumber = Lead::model()->find('mobile = "' . @$mobileNumber . '" AND createdOn > "' . @$beforethreemonth . '" AND status = "Active" AND leadId != "' . @$leadId . '" ');
  963. if (empty($checkDuplicateNumber))
  964. {
  965. $model->save(false);
  966. Yii::app()->user->setFlash('lead_msg_success', 'Successfully Inserted');
  967. }
  968. else
  969. {
  970. $duplicateLeadId = $checkDuplicateNumber->leadId;
  971. $model->leadStatusId = '10';
  972. $model->duplicateLeadId = @$duplicateLeadId;
  973. $model->currentAllocatedId = $checkDuplicateNumber->currentAllocatedId;
  974. $model->save(false);
  975. Yii::app()->user->setFlash('lead_msg_success', 'Successfully Inserted');
  976. }
  977. }
  978. else
  979. {
  980. $model->leadStatusId = '36';
  981. $model->save(false);
  982. Yii::app()->user->setFlash('lead_msg_success', 'Junk Lead');
  983. }
  984. self::updateLeadAllCount($model->leadStatusId);
  985. $this->redirect(array('leads/lead_list'));
  986. // $model->save(false);
  987. // $this->redirect(array('leads/lead_list'));
  988. }
  989. }
  990. }
  991. if ($model->leadStatusId == 36)
  992. {
  993. self::updateLeadAllCount($model->leadStatusId);
  994. $model->save(false);
  995. $this->redirect(array('leads/lead_list'));
  996. }
  997. else
  998. {
  999. if ($model->validate())
  1000. {
  1001. $mobileNumber = $_POST['Lead']['mobile'];
  1002. $checkJunkNumber = JunkNumbersMaster::model()->find('junkLeadNumber = "' . @$mobileNumber . '"');
  1003. if (empty($checkJunkNumber))
  1004. {
  1005. $beforethreemonth = time() - 7776000;
  1006. $checkDuplicateNumber = Lead::model()->find('mobile = "' . @$mobileNumber . '" AND createdOn > "' . @$beforethreemonth . '" AND status = "Active" AND leadId != "' . @$leadId . '" ');
  1007. if (empty($checkDuplicateNumber))
  1008. {
  1009. self::updateLeadAllCount($model->leadStatusId);
  1010. $model->save();
  1011. Yii::app()->user->setFlash('lead_msg_success', 'Successfully Inserted');
  1012. }
  1013. else
  1014. {
  1015. $duplicateLeadId = $checkDuplicateNumber->leadId;
  1016. $model->leadStatusId = '10';
  1017. $model->duplicateLeadId = @$duplicateLeadId;
  1018. self::updateLeadAllCount($model->leadStatusId);
  1019. $model->save();
  1020. Yii::app()->user->setFlash('lead_msg_success', 'Successfully Inserted');
  1021. }
  1022. }
  1023. else
  1024. {
  1025. $model->leadStatusId = '36';
  1026. self::updateLeadAllCount($model->leadStatusId);
  1027. $model->save();
  1028. Yii::app()->user->setFlash('lead_msg_success', 'Junk Lead');
  1029. }
  1030. $this->redirect(array('leads/lead_list'));
  1031. }
  1032. else
  1033. {
  1034. $this->render('create_lead', array('model' => $model));
  1035. }
  1036. }
  1037. }
  1038. else
  1039. {
  1040. $this->render('create_lead', array('model' => $model));
  1041. }
  1042. }
  1043. /**
  1044. * AllocateLeads.
  1045. * @return void
  1046. */
  1047. public function actionAllocateLeads()
  1048. {
  1049. $Id = $_REQUEST['userids'];
  1050. $teamId = @$_REQUEST['Team']['teamId'];
  1051. $userId = $_REQUEST['Team']['teamMemberId'];
  1052. $updatedBy = @$_SESSION['id'];
  1053. $userdetails = Yii::app()->db->createCommand("select firstName,lastName from user where id=" . $userId . " ")->queryAll();
  1054. $actionurl = @$_REQUEST['actionurl'];
  1055. $paginationsize = Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize'])?Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']):25;
  1056. $myArray = array();
  1057. $responseAll = array();
  1058. $t = 0;
  1059. $teamIdString = @$teamId ? '' : ",teamId = $teamId, ";
  1060. //Yii::app()->db->createCommand('START TRANSACTION;')->execute();
  1061. foreach ($Id as $key => $value)
  1062. {
  1063. $model = new AllocatedLeads();
  1064. $model->scenario = 'AllocatedLeads';
  1065. $model->setAttributes(array(
  1066. 'currentAllocatedDate' => time(), //additional data you want to insert
  1067. 'createdOn' => time(), //additional data you want to insert
  1068. 'updatedOn' => time(), //additional
  1069. 'updatedBy' => @$updatedBy, //additional
  1070. 'createdBy' => @$updatedBy, //additional
  1071. 'leadStatusId' => '35', //additional //additional
  1072. ));
  1073. $leadId = @$value;
  1074. $model->leadId = @$value;
  1075. $model->userId = @$userId;
  1076. $model->teamId = @$teamId;
  1077. //echo @$teamId.' - '.@$userId.' - '.@$leadId;
  1078. $model->allocatedId = null;
  1079. $model->isNewRecord = true;
  1080. $model->save();
  1081. /* Comment by shakti as handled below
  1082. $model = new Lead();
  1083. $model->scenario = 'Lead';
  1084. */
  1085. //currentAllocateId is getting updated so update it after all processessing.
  1086. /*
  1087. $updatedOn = time();
  1088. Lead::model()->updateByPk(@$value, array('currentAllocatedId' => @$userId, 'leadStatusId' => '35', 'updatedBy' => @$updatedBy, 'updatedOn' => @$updatedOn, 'currentAllocatedDate' => @$updatedOn));
  1089. */
  1090. // $responseAll[$t]['ownername'] = $userdetails[0]['firstName'] . $userdetails[0]['lastName'];
  1091. // $responseAll[$t]['classname'] = "owner_" . @$value;
  1092. // $responseAll[$t]['rowclass'] = @$value;
  1093. // $myArray[0][$t] = $responseAll[$t];
  1094. // $myArray[1]['roleId'] = Yii::app()->session->get('roleId');
  1095. // $myArray[2]['actionurl']=$actionurl;
  1096. // $myArray[3]['paginationsize']=$paginationsize;
  1097. // $t++;
  1098. $leadRecord = Yii::app()->db->createCommand("select leadStatusId, currentAllocatedId from lead where leadId = $value")->queryRow();
  1099. $leadStatus = $leadRecord['leadStatusId'];
  1100. $currentAllocatedId = $leadRecord['currentAllocatedId'];
  1101. $updatedOn = time();
  1102. if(BaseController::getConfigurationValue('leadallcount'))
  1103. {
  1104. //if (Yii::app()->session->get('type') == 'Superadmin')
  1105. if ($leadStatus == 34 || (Yii::app()->session->get('type') == 'superadmin' && $leadStatus == 10))
  1106. {
  1107. //Super : status 34(new)/10(duplicate) count decrement
  1108. Yii::app()->db->createCommand("update leadallcount set count = count - 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1109. where userid = 1 && accesskey = '" . date('Y') . '-' . date('m') . "' && leadtype = $leadStatus")->execute();
  1110. Yii::app()->db->createCommand("update leadallcount set count = count - 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1111. where userid = 1 && accesskey = '" . date('Y') . "' && leadtype = $leadStatus")->execute();
  1112. //Super : status 35(allocated) count increment
  1113. Yii::app()->db->createCommand("update leadallcount set count = count + 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1114. where userid = 1 && accesskey = '" . date('Y') . '-' . date('m') . "' && leadtype = 35")->execute();
  1115. Yii::app()->db->createCommand("update leadallcount set count = count + 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1116. where userid = 1 && accesskey = '" . date('Y') . "' && leadtype = 35")->execute();
  1117. //New Allocated Teamlead : status 35(allocated) count increment
  1118. Yii::app()->db->createCommand("update leadallcount set count = count + 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1119. where userid = $userId && accesskey = '" . date('Y') . '-' . date('m') . "' && leadtype = 35")->execute();
  1120. Yii::app()->db->createCommand("update leadallcount set count = count + 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1121. where userid = $userId && accesskey = '" . date('Y') . "' && leadtype = 35")->execute();
  1122. }
  1123. else
  1124. {
  1125. if ($leadStatus != 35)
  1126. {
  1127. //Super Admin : status count decrement
  1128. Yii::app()->db->createCommand("update leadallcount set count = count - 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1129. where userid = 1 && accesskey = '" . date('Y') . '-' . date('m') . "' && leadtype = $leadStatus")->execute();
  1130. Yii::app()->db->createCommand("update leadallcount set count = count - 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1131. where userid = 1 && accesskey = '" . date('Y') . "' && leadtype = $leadStatus")->execute();
  1132. //Super Admin: status 35(allocated) count increment
  1133. Yii::app()->db->createCommand("update leadallcount set count = count + 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1134. where userid = 1 && accesskey = '" . date('Y') . '-' . date('m') . "' && leadtype = 35")->execute();
  1135. Yii::app()->db->createCommand("update leadallcount set count = count + 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1136. where userid = 1 && accesskey = '" . date('Y') . "' && leadtype = 35")->execute();
  1137. }
  1138. //current allocated lead/caller : status 35(allocated) count decrement
  1139. Yii::app()->db->createCommand("update leadallcount set count = count - 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1140. where userid = $currentAllocatedId && accesskey = '" . date('Y') . '-' . date('m') . "' && leadtype = $leadStatus")->execute();
  1141. Yii::app()->db->createCommand("update leadallcount set count = count - 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1142. where userid = $currentAllocatedId && accesskey = '" . date('Y') . "' && leadtype = $leadStatus")->execute();
  1143. //New Allocated Teamlead : status 35(allocated) count increment
  1144. Yii::app()->db->createCommand("update leadallcount set count = count + 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1145. where userid = $userId && accesskey = '" . date('Y') . '-' . date('m') . "' && leadtype = 35")->execute();
  1146. Yii::app()->db->createCommand("update leadallcount set count = count + 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1147. where userid = $userId && accesskey = '" . date('Y') . "' && leadtype = 35")->execute();
  1148. }
  1149. }
  1150. //Added by shakti upto here
  1151. Yii::app()->db->createCommand("update lead set currentAllocatedId = $userId, leadStatusId = 35, currentAllocatedDate = $updatedOn ,
  1152. updatedBy = $updatedBy, updatedOn = $updatedOn, currentAllocatedDate = $updatedOn where leadId = $leadStatus")->execute();
  1153. $updatedOn = time();
  1154. Lead::model()->updateByPk(@$value, array('currentAllocatedId' => @$userId, 'leadStatusId' => '35', 'updatedBy' => @$updatedBy, 'updatedOn' => @$updatedOn, 'currentAllocatedDate' => @$updatedOn));
  1155. $responseAll[$t]['ownername'] = $userdetails[0]['firstName'] . $userdetails[0]['lastName'];
  1156. $responseAll[$t]['classname'] = "owner_" . @$value;
  1157. $responseAll[$t]['rowclass'] = @$value;
  1158. $myArray[0][$t] = $responseAll[$t];
  1159. $myArray[1]['roleId'] = Yii::app()->session->get('roleId');
  1160. $myArray[2]['actionurl']=$actionurl;
  1161. $myArray[3]['paginationsize']=$paginationsize;
  1162. $t++;
  1163. }
  1164. //Yii::app()->db->createCommand('COMMIT;')->execute();
  1165. if (Yii::app()->session->get('type') == 'superadmin')
  1166. {
  1167. echo json_encode($myArray);
  1168. }
  1169. else if (Yii::app()->session->get('roleId') == 4)
  1170. {
  1171. echo json_encode($myArray);
  1172. }
  1173. else
  1174. {
  1175. $myArray = array('somethingwrong');
  1176. echo json_encode($myArray);
  1177. }
  1178. exit;
  1179. }
  1180. public function actionAllocateLeads_17nov2014()
  1181. {
  1182. $Id = $_REQUEST['userids'];
  1183. $teamId = @$_REQUEST['Team']['teamId'];
  1184. $userId = $_REQUEST['Team']['teamMemberId'];
  1185. $updatedBy = @$_SESSION['id'];
  1186. foreach($Id as $key=>$value){
  1187. $model = new AllocatedLeads();
  1188. $model->scenario = 'AllocatedLeads';
  1189. $model->setAttributes(array(
  1190. 'currentAllocatedDate' => time(), //additional data you want to insert
  1191. //'createdOn' => time(), //additional data you want to insert
  1192. 'updatedOn' => time(), //additional
  1193. 'updatedBy' => @$updatedBy, //additional
  1194. 'createdBy' => @$updatedBy, //additional
  1195. 'leadStatusId' => '35', //additional //additional
  1196. ));
  1197. $leadId = @$value;
  1198. $model->leadId = @$value;
  1199. $model->userId = @$userId;
  1200. $model->teamId = @$teamId;
  1201. //echo @$teamId.' - '.@$userId.' - '.@$leadId;
  1202. $model->allocatedId = null;
  1203. $model->isNewRecord = true;
  1204. $model->save();
  1205. $model=new Lead();
  1206. $model->scenario = 'Lead';
  1207. $updatedOn = time();
  1208. Lead::model()->updateByPk(@$value, array('currentAllocatedId'=>@$userId,'leadStatusId'=>'35','updatedBy'=>@$updatedBy,'updatedOn'=>@$updatedOn,'currentAllocatedDate'=>@$updatedOn));
  1209. }
  1210. $red = @$_REQUEST['red'];
  1211. if($this->action->id=='AllocateLeads' && $red == 1) {
  1212. $this->redirect(array('leads/lead_list'));
  1213. } else {
  1214. $this->redirect(array('leads/fresh_leads'));
  1215. }
  1216. //$this->redirect(array('leads/lead_list'));
  1217. }
  1218. public function actionAllocateLeadswithcount()
  1219. {
  1220. $Id = $_REQUEST['userids'];
  1221. $teamId = @$_REQUEST['Team']['teamId'];
  1222. $userId = $_REQUEST['Team']['teamMemberId'];
  1223. $updatedBy = @$_SESSION['id'];
  1224. foreach($Id as $key=>$value){
  1225. $model = new AllocatedLeads();
  1226. $model->scenario = 'AllocatedLeads';
  1227. $model->setAttributes(array(
  1228. 'currentAllocatedDate' => time(), //additional data you want to insert
  1229. //'createdOn' => time(), //additional data you want to insert
  1230. 'updatedOn' => time(), //additional
  1231. 'updatedBy' => @$updatedBy, //additional
  1232. 'createdBy' => @$updatedBy, //additional
  1233. 'leadStatusId' => '35', //additional //additional
  1234. ));
  1235. $leadId = @$value;
  1236. $model->leadId = @$value;
  1237. $model->userId = @$userId;
  1238. $model->teamId = @$teamId;
  1239. //echo @$teamId.' - '.@$userId.' - '.@$leadId;
  1240. $model->allocatedId = null;
  1241. $model->isNewRecord = true;
  1242. $model->save();
  1243. $model=new Lead();
  1244. $model->scenario = 'Lead';
  1245. $updatedOn = time();
  1246. //Lead::model()->updateByPk(@$value, array('currentAllocatedId'=>@$userId,'leadStatusId'=>'35','updatedBy'=>@$updatedBy,'updatedOn'=>@$updatedOn,'currentAllocatedDate'=>@$updatedOn));
  1247. }
  1248. $red = @$_REQUEST['red'];
  1249. $chkleadAllocatedOrNot = Lead::model()->findByPk($leadId);
  1250. $oldallocatedid = $chkleadAllocatedOrNot['currentAllocatedId'];
  1251. if(isset($oldallocatedid) && !empty($oldallocatedid)){
  1252. $checkLeadExistorNot=Leadallcount::model()->findByAttributes(array('userid'=>$oldallocatedid,'key'=>'2014'));
  1253. if(count($checkLeadExistorNot) > 0){
  1254. Leadallcount::model()->updateByPk(@$checkLeadExistorNot['id'], array('userid'=>@$oldallocatedid,'key'=>'2014','value'=>'35','updatedBy'=>@$updatedBy,'updatedOn'=>@$updatedOn,'currentAllocatedDate'=>@$updatedOn));
  1255. } else {
  1256. $leadcount = new Leadallcount();
  1257. $leadcount->setAttributes(array(
  1258. 'userid' => $oldallocatedid, //additional data you want to insert
  1259. 'key' => 2014, //additional data you want to insert
  1260. 'value' => 1, //additional data you want to insert
  1261. 'createdOn' => time(), //additional data you want to insert
  1262. 'updatedOn' => time(), //additional
  1263. 'updatedBy' => time(), //additional
  1264. 'createdBy' => time(), //additional //additional
  1265. ));
  1266. $leadcount->save(false);
  1267. }
  1268. }
  1269. /*$leadcount->setAttributes(array(
  1270. 'userid' => time(), //additional data you want to insert
  1271. 'key' => 2014, //additional data you want to insert
  1272. 'value' => 1, //additional data you want to insert
  1273. 'createdOn' => time(), //additional data you want to insert
  1274. 'updatedOn' => time(), //additional
  1275. 'updatedBy' => time(), //additional
  1276. 'createdBy' => time(), //additional //additional
  1277. ));
  1278. $leadcount->save(false);*/
  1279. die;
  1280. if($this->action->id=='AllocateLeads' && $red == 1) {
  1281. $this->redirect(array('leads/lead_list'));
  1282. } else {
  1283. $this->redirect(array('leads/fresh_leads'));
  1284. }
  1285. //$this->redirect(array('leads/lead_list'));
  1286. }
  1287. /**
  1288. * This is the 'lead_list_allocator' action that is invoked
  1289. * when an action is not explicitly requested by users.
  1290. */
  1291. public function actionlead_assign()
  1292. {
  1293. $model = new Lead();
  1294. $model->scenario = 'Lead';
  1295. $leadId = $_REQUEST['AssignLead']['leadId'];
  1296. $userId = $_REQUEST['AssignLead']['userId'];
  1297. $assign = $_REQUEST['AssignLead']['assign'];
  1298. if ($leadId != '')
  1299. {
  1300. $updatedOn = time();
  1301. $chkleadStatus = Lead::model()->findByPk($leadId);
  1302. $existsOrNot = $chkleadStatus['leadStatusId'];
  1303. $leadStatusIdUpdate = $existsOrNot ? $existsOrNot : '34';
  1304. //Added by shakti. Mixed code
  1305. $updatedBy = Yii::app()->session['id'];
  1306. $prevCurrentAllocatedId = $chkleadStatus->currentAllocatedId;
  1307. $leadStatusId = $chkleadStatus->leadStatusId;
  1308. $accesskeyYear = date('Y', $chkleadStatus->currentAllocatedDate);
  1309. $accesskeyMonth = date('m', $chkleadStatus->currentAllocatedDate);
  1310. if ($leadStatusIdUpdate == 34)
  1311. {
  1312. $leadStatusIdUpdate = 35;
  1313. }
  1314. else
  1315. {
  1316. $leadStatusIdUpdate = $leadStatusIdUpdate;
  1317. }
  1318. if ($assign == 'open')
  1319. {
  1320. Lead::model()->updateByPk(@$leadId, array('currentAllocatedId' => '', 'status' => 'Active', 'leadStatusId' => 34, 'updatedBy' => @$userId, 'updatedOn' => @$updatedOn, 'currentAllocatedDate' => ''));
  1321. if(BaseController::getConfigurationValue('leadallcount'))
  1322. {
  1323. Yii::app()->db->createCommand("update leadallcount set count = count - 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1324. where userid = $prevCurrentAllocatedId and value = $leadStatusId
  1325. and accesskey = '$accesskeyYear'")->execute();
  1326. Yii::app()->db->createCommand("update leadallcount set count = count - 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1327. where userid = $prevCurrentAllocatedId and value = $leadStatusId
  1328. and accesskey = '$accesskeyYear-$accesskeyMonth'")->execute();
  1329. }
  1330. }
  1331. elseif ($assign == 'self')
  1332. {
  1333. Lead::model()->updateByPk(@$leadId, array('currentAllocatedId' => @$userId, 'status' => 'Allocated', 'leadStatusId' => @$leadStatusIdUpdate, 'updatedBy' => @$userId, 'updatedOn' => @$updatedOn, 'currentAllocatedDate' => @$updatedOn));
  1334. if ($updatedBy != $prevCurrentAllocatedId && BaseController::getConfigurationValue('leadallcount'))
  1335. {
  1336. Yii::app()->db->createCommand("update leadallcount set count = count + 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1337. where userid = $updatedBy and value = $leadStatusId
  1338. and accesskey = '$accesskeyYear'")->execute();
  1339. Yii::app()->db->createCommand("update leadallcount set count = count + 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1340. where userid = $updatedBy and value = $leadStatusId
  1341. and accesskey = '$accesskeyYear-$accesskeyMonth'")->execute();
  1342. }
  1343. }
  1344. else
  1345. {
  1346. Lead::model()->updateByPk(@$leadId, array('currentAllocatedId' => @$assign, 'status' => 'Allocated', 'leadStatusId' => @$leadStatusIdUpdate, 'updatedBy' => @$userId, 'updatedOn' => @$updatedOn, 'currentAllocatedDate' => @$updatedOn));
  1347. if(BaseController::getConfigurationValue('leadallcount'))
  1348. {
  1349. Yii::app()->db->createCommand("update leadallcount set count = count + 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1350. where userid = $assign and value = $leadStatusId
  1351. and accesskey = '$accesskeyYear-$accesskeyMonth'")->execute();
  1352. Yii::app()->db->createCommand("update leadallcount set count = count - 1, updatedOn = $updatedOn, updatedBy = $updatedBy
  1353. where userid = $prevCurrentAllocatedId and value = $leadStatusId
  1354. and accesskey = '$accesskeyYear-$accesskeyMonth'")->execute();
  1355. }
  1356. }
  1357. //Added by shakti upto here
  1358. echo CJSON::encode(array(
  1359. 'status' => 'success'
  1360. ));
  1361. Yii::app()->end();
  1362. //$this->redirect(array('leads/leads_details', 'leadId'=>@$leadId));
  1363. }
  1364. else
  1365. {
  1366. $this->redirect(array('leads/lead_list'));
  1367. }
  1368. }
  1369. /**
  1370. * This is the 'roles' action that is invoked
  1371. * when an action is not explicitly requested by users.
  1372. */
  1373. public function actionarchive_leads()
  1374. {
  1375. // renders the view file 'protected/views/site/index.php'
  1376. // using the default layout 'protected/views/layouts/main.php'
  1377. $model=new Lead();
  1378. //$model=Lead::model()->findAll();
  1379. $this->render('archive_leads',array('model'=>$model));
  1380. }
  1381. /**
  1382. * This is the 'roles' action that is invoked
  1383. * when an action is not explicitly requested by users.
  1384. */
  1385. public function actionbulk_import_leads()
  1386. {
  1387. // renders the view file 'protected/views/site/index.php'
  1388. // using the default layout 'protected/views/layouts/main.php'
  1389. $model=new Lead();
  1390. $this->render('bulk_import_lead',array('model'=>$model));
  1391. }
  1392. /**
  1393. * This is the 'roles' action that is invoked
  1394. * when an action is not explicitly requested by users.
  1395. */
  1396. public function actionjunk_leads()
  1397. {
  1398. // renders the view file 'protected/views/site/index.php'
  1399. // using the default layout 'protected/views/layouts/main.php'
  1400. $this->render('junk_leads');
  1401. }
  1402. /**
  1403. * This is the 'module master' action that is invoked
  1404. * when an action is not explicitly requested by users.
  1405. */
  1406. public function actionmodule_master()
  1407. {
  1408. // renders the view file 'protected/views/site/index.php'
  1409. // using the default layout 'protected/views/layouts/main.php'
  1410. $model=new ModuleMaster();
  1411. $model->scenario = 'ModuleMaster';
  1412. if(!empty($_GET['moduleId']))
  1413. {
  1414. $moduleId=$_GET['moduleId'];
  1415. $model=ModuleMaster::model()->findByPk($moduleId);
  1416. }
  1417. if(!empty($_POST['ModuleMaster']['moduleId']))
  1418. {
  1419. $moduleId=$_POST['ModuleMaster']['moduleId'];
  1420. $model=ModuleMaster::model()->findByPk($moduleId);
  1421. }
  1422. if(isset($_POST['ModuleMaster']))
  1423. {
  1424. $model->setAttributes(array(
  1425. 'createdOn' => time(), //additional data you want to insert
  1426. 'updatedOn' => time(), //additional
  1427. 'updatedBy' => time(), //additional
  1428. 'createdBy' => time(),
  1429. 'status' => 'Activated', //additional //additional
  1430. ));
  1431. foreach($_POST['ModuleMaster'] as $name=>$value)
  1432. {
  1433. $model->$name=$value;
  1434. }
  1435. if($model->validate()){
  1436. $model->save();
  1437. $model2=ModuleMaster::model()->findAll();
  1438. $this->render('module_master',array('model'=>$model,'model2'=>$model2));
  1439. Yii::app()->user->setFlash('module_master_msg_success','Successfully Inserted');
  1440. } else {
  1441. Yii::app()->user->setFlash('module_master_msg_error','Please check. error occured');
  1442. $this->render('module_master',array('model'=>$model));
  1443. }
  1444. } else {
  1445. $model2=ModuleMaster::model()->findAll();
  1446. //Yii::app()->user->setFlash('lead_stage_msg_error','Please check. error occured');
  1447. $this->render('module_master',array('model'=>$model,'model2'=>$model2));
  1448. }
  1449. }
  1450. /**
  1451. * This is the action to handle external exceptions.
  1452. */
  1453. public function actionError()
  1454. {
  1455. if($error=Yii::app()->errorHandler->error)
  1456. {
  1457. if(Yii::app()->request->isAjaxRequest)
  1458. echo $error['message'];
  1459. else
  1460. $this->render('error', $error);
  1461. }
  1462. }
  1463. /**
  1464. * Displays the contact page
  1465. */
  1466. public function actionContact()
  1467. {
  1468. $model=new ContactForm;
  1469. if(isset($_POST['ContactForm']))
  1470. {
  1471. $model->attributes=$_POST['ContactForm'];
  1472. if($model->validate())
  1473. {
  1474. $name='=?UTF-8?B?'.base64_encode($model->name).'?=';
  1475. $subject='=?UTF-8?B?'.base64_encode($model->subject).'?=';
  1476. $headers="From: $name <{$model->email}>\r\n".
  1477. "Reply-To: {$model->email}\r\n".
  1478. "MIME-Version: 1.0\r\n".
  1479. "Content-type: text/plain; charset=UTF-8";
  1480. mail(Yii::app()->params['adminEmail'],$subject,$model->body,$headers);
  1481. Yii::app()->user->setFlash('contact','Thank you for contacting us. We will respond to you as soon as possible.');
  1482. $this->refresh();
  1483. }
  1484. }
  1485. $this->render('contact',array('model'=>$model));
  1486. }
  1487. /**
  1488. * Displays the login page
  1489. */
  1490. public function actionLogin()
  1491. {
  1492. $model=new User;
  1493. // if it is ajax validation request
  1494. if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
  1495. {
  1496. echo CActiveForm::validate($model);
  1497. Yii::app()->end();
  1498. }
  1499. // collect user input data
  1500. if(isset($_POST['User']))
  1501. {
  1502. $model->attributes=$_POST['User'];
  1503. // validate user input and redirect to the previous page if valid
  1504. if($model->validate() && $model->login()){
  1505. $this->redirect(array('masters/dashboard'));
  1506. } else {
  1507. $this->redirect(Yii::app()->user->returnUrl);
  1508. }
  1509. }
  1510. // display the login form
  1511. $this->render('login',array('model'=>$model));
  1512. }
  1513. /**
  1514. * Logs out the current user and redirect to homepage.
  1515. */
  1516. public function actionLogout()
  1517. {
  1518. setcookie ('PHPSESSID', '', time(), '/', '', 0, 0); // Destroy the cookie.
  1519. Yii::app()->user->logout();
  1520. $this->redirect(Yii::app()->homeUrl);
  1521. }
  1522. public function getPageType()
  1523. {
  1524. return "Leads";
  1525. }
  1526. public function init(){
  1527. parent::init();
  1528. $obj =new RecentlyViewedController(); // preparing object
  1529. $data=$obj->actionUserRoleAccess();
  1530. $moduleArray=array();
  1531. if(Yii::app()->session->get('type')=='superadmin'){
  1532. $moduleArray['read']='yes';
  1533. $moduleArray['write']='yes';
  1534. $moduleArray['delete']='yes';
  1535. }else{
  1536. foreach($data as $key=>$value){
  1537. if($data[$key]->modules->moduleName=='Leads'){
  1538. $moduleArray['moduleName']=$data[$key]->modules->moduleName;
  1539. $moduleArray['read']=$data[$key]->read;
  1540. $moduleArray['write']=$data[$key]->write;
  1541. $moduleArray['delete']=$data[$key]->delete;
  1542. }
  1543. }
  1544. }
  1545. return $moduleArray;
  1546. }
  1547. public function getNameFromNumber($num) {
  1548. $numeric = $num % 26;
  1549. $letter = chr(65 + $numeric);
  1550. $num2 = intval($num / 26);
  1551. if ($num2 > 0) {
  1552. return getNameFromNumber($num2 - 1) . $letter;
  1553. } else {
  1554. return $letter;
  1555. }
  1556. }
  1557. /*function actionexportArchiveList()
  1558. {
  1559. // generate a resultset
  1560. $model=new User;
  1561. $model=User::model()->findAll();
  1562. // render data to xlsx format and echo resultant file back to browser.
  1563. ExcelExporter::sendAsXLS($model, true, 'closedLeads.xls');
  1564. }*/
  1565. public function actionDownloadLeadTemp(){
  1566. Yii::import('ext.phpexcel.XPHPExcel');
  1567. $objPHPExcel= XPHPExcel::createPHPExcel();
  1568. $objPHPExcel->getProperties()->setCreator("LeadTemplate")
  1569. ->setLastModifiedBy("LeadTemplate")
  1570. ->setTitle("LeadTemplate")
  1571. ->setSubject("LeadTemplate")
  1572. ->setDescription("LeadTemplate.")
  1573. ->setKeywords("LeadTemplate")
  1574. ->setCategory("LeadTemplate");
  1575. //echo $total_excelColumns=$this->getNameFromNumber(4);
  1576. $total_excelColumns='I';
  1577. // Rename worksheet
  1578. $objPHPExcel->getActiveSheet()->setTitle('ClosedLeads');
  1579. $objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(25);
  1580. $objPHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight(20);
  1581. $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(30);
  1582. $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
  1583. $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
  1584. $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(30);
  1585. $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30);
  1586. $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(30);
  1587. $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(30);
  1588. $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(30);
  1589. $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(30);
  1590. $objPHPExcel->getActiveSheet()->duplicateStyleArray(
  1591. array(
  1592. 'font' => array(
  1593. 'name' => 'Times New Roman',
  1594. 'bold' => true,
  1595. 'italic' => false,
  1596. 'size' => 12
  1597. ),
  1598. 'borders' => array(
  1599. 'top' => array('style' => PHPExcel_Style_Border::BORDER_DOUBLE),
  1600. 'bottom' => array('style' => PHPExcel_Style_Border::BORDER_DOUBLE),
  1601. 'left' => array('style' => PHPExcel_Style_Border::BORDER_DOUBLE),
  1602. 'right' => array('style' => PHPExcel_Style_Border::BORDER_DOUBLE)
  1603. ),
  1604. 'alignment' => array(
  1605. 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
  1606. 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
  1607. 'wrap' => true
  1608. )
  1609. ),
  1610. 'A1:'.$total_excelColumns.'1'
  1611. );
  1612. // Set active sheet index to the first sheet, so Excel opens this as the first sheet
  1613. // Add some data
  1614. $objPHPExcel->setActiveSheetIndex(0)
  1615. ->setCellValue('A1', 'Name')
  1616. ->setCellValue('B1', 'City')
  1617. ->setCellValue('C1', 'Email')
  1618. ->setCellValue('D1', 'Mobile')
  1619. ->setCellValue('E1', 'Suminsured')
  1620. ->setCellValue('F1', 'Age')
  1621. ->setCellValue('G1', 'No. Of Members')
  1622. ->setCellValue('H1', 'Date on submit')
  1623. ->setCellValue('I1', 'Lead Source');
  1624. // Miscellaneous glyphs, UTF-8
  1625. $objPHPExcel->setActiveSheetIndex(0)
  1626. ->setCellValue('A2', 'Lead Name')
  1627. ->setCellValue('B2', 'city')
  1628. ->setCellValue('C2', 'test@yesk.com')
  1629. ->setCellValue('D2', '9999999999')
  1630. ->setCellValue('E2', '56')
  1631. ->setCellValue('F2', '23')
  1632. ->setCellValue('G2', 'test')
  1633. ->setCellValue('H2', '07-Sep-2013')
  1634. ->setCellValue('I2', 'test');
  1635. //To create new sheet in current file
  1636. /*$objPHPExcel->createSheet(1);
  1637. $objPHPExcel->setActiveSheetIndex(1);
  1638. $objPHPExcel->getActiveSheet()->setTitle('Title');
  1639. */
  1640. // Redirect output to a client�s web browser (Excel5)
  1641. header('Content-Type: application/vnd.ms-excel');
  1642. header('Content-Disposition: attachment;filename="LeadTemplates.xls"');
  1643. header('Cache-Control: max-age=0');
  1644. // If you're serving to IE 9, then the following may be needed
  1645. header('Cache-Control: max-age=1');
  1646. // If you're serving to IE over SSL, then the following may be needed
  1647. header ('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
  1648. header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
  1649. header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
  1650. header ('Pragma: public'); // HTTP/1.0
  1651. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
  1652. $objWriter->save('php://output');
  1653. Yii::app()->end();
  1654. }
  1655. public function actionImportLeadTemplate(){
  1656. $model=new lead();
  1657. $data='';
  1658. $final_arr=@$_POST['final_arr']?@$_POST['final_arr']:'';
  1659. if(isset($_POST['ImportLeads']) && empty($final_arr) && !empty($_FILES['Lead']['name']['import'])){
  1660. Yii::import('ext.phpexcelreader.JPhpExcelReader');
  1661. $model->attributes='import';
  1662. $model->import=CUploadedFile::getInstance($model,'import');
  1663. $prefix=substr(time(),0,5);
  1664. $folder = '/tempdata';
  1665. $model->import->saveAs($folder.$prefix.$model->import);
  1666. $data=new JPhpExcelReader($folder.$prefix.$model->import);
  1667. //$this->render('bulk_import_lead',array('data'=>$data,'model'=>$model));
  1668. //$this->redirect(Yii::app()->createUrl('leads/bulk_import_leads'),array('data'=>$data,'model'=>$model));
  1669. $this->render('bulk_import_lead',array('data'=>$data,'model'=>$model));
  1670. }
  1671. if(isset($_POST['ImportLeads']) && !empty($final_arr) && isset($final_arr) && empty($_FILES['Lead']['name']['import'])){
  1672. $final_arr = unserialize(urldecode($_POST["final_arr"]));
  1673. $dateTime=time();
  1674. /*echo '<pre>';
  1675. print_r($final_arr);*/
  1676. for($i=0;$i<sizeof($final_arr);$i++)
  1677. {
  1678. $leadStatusId = '0';
  1679. $duplicateLeadId = '0';
  1680. $currentAllocatedId = '0';
  1681. $junkNumberQuery = Yii::app()->db->createCommand("SELECT `junkLeadNumberId` FROM `junkLeadNumberMaster` WHERE `junkLeadNumber` = '".@$final_arr[$i]['mobile']."' ")->queryAll();
  1682. $junkNumberResult = $junkNumberQuery;
  1683. $fetchAgentDetails=LeadSourceMaster::model()->findByPk($final_arr[$i]['leadSourceId']);
  1684. //$duplicateQuery = Yii::app()->db->createCommand("SELECT `leadId` FROM `lead` WHERE `mobile`= '".@$final_arr[$i]['mobile']."' ")->queryAll();(Original, changed below by Baljeet)
  1685. $duplicateQuery = Yii::app()->db->createCommand("SELECT `leadId`,`currentAllocatedId` FROM `lead` WHERE `mobile`= '".@$final_arr[$i]['mobile']."' order by leadId ASC LIMIT 1")->queryAll();
  1686. $duplicateResult = ($duplicateQuery);
  1687. //echo '<br>duplicateResult----------'.count($duplicateResult);
  1688. if(count($junkNumberResult) > 0){
  1689. $leadStatusId = '36';
  1690. $duplicateLeadId = '';
  1691. $currentAllocatedId = '';
  1692. } elseif(count($duplicateResult)>0){
  1693. $leadStatusId = '10';
  1694. $duplicateLeadId = @$duplicateResult[0]['leadId'];
  1695. $currentAllocatedId = @$duplicateResult[0]['currentAllocatedId']; //added by baljeet
  1696. } else {
  1697. $leadStatusId = '34';
  1698. $duplicateLeadId = '';
  1699. $currentAllocatedId = '';
  1700. }
  1701. /*echo '<br>leadStatusId---'.$leadStatusId;
  1702. echo '<br>duplicateLeadId---'.$duplicateLeadId;
  1703. echo '<br>currentAllocatedId---'.$currentAllocatedId;*/
  1704. $model=new lead();
  1705. $model->name=$final_arr[$i]['name'];
  1706. $model->cityId=$final_arr[$i]['cityId'];
  1707. $model->email=$final_arr[$i]['email'];
  1708. $model->mobile=$final_arr[$i]['mobile'];
  1709. $model->si=$final_arr[$i]['suminsured'];
  1710. $model->age=$final_arr[$i]['age'];
  1711. $model->members=$final_arr[$i]['noofmembers'];
  1712. $model->dateonSubmit=$final_arr[$i]['dateonsubmit'];
  1713. $model->leadSourceId=$final_arr[$i]['leadSourceId'];
  1714. $model->leadStatusId=$leadStatusId;
  1715. $model->duplicateLeadId=@$duplicateLeadId;
  1716. $model->currentAllocatedId=@$currentAllocatedId;
  1717. $model->productId='1';
  1718. $model->status='Active';
  1719. $model->createdOn=$dateTime;
  1720. $model->createdBy=Yii::app()->session->get('id');
  1721. $model->updatedOn=$dateTime;
  1722. $model->updatedBy=Yii::app()->session->get('id');
  1723. $model->isBulkImport='YES';
  1724. $model->agentId = @$fetchAgentDetails->leadSourceCode;
  1725. $model->ws_agentid = @$fetchAgentDetails->leadSourceCode;
  1726. $model->isNewRecord = true;
  1727. $model->save(false);
  1728. }
  1729. $this->redirect(array('leads/lead_list'));
  1730. }
  1731. if(isset($_POST['ImportLeads']) && empty($final_arr) && empty($_FILES['Lead']['name']['import'])){
  1732. $model->validate();
  1733. $this->render('bulk_import_lead',array('model'=>$model));
  1734. }
  1735. }
  1736. public function actionleadSearch()
  1737. {
  1738. if (@$_REQUEST['lead']['leadSearchBox'] == '' && @$_REQUEST['mob'] == '')
  1739. {
  1740. $this->redirect(array('leads/lead_list'));
  1741. }
  1742. else
  1743. {
  1744. $searched = new Lead();
  1745. $this->render('lead_search', array('searched' => $searched->search()));
  1746. }
  1747. }
  1748. public function actionExportExcel()
  1749. {
  1750. // It calls the actionCreateExcel to generates excel reports'
  1751. $this->actionCreateExcel();
  1752. }
  1753. public function actionCreateExcel(){
  1754. //Here is the code to set conditions for fetch records from database
  1755. $criteria = new CDbCriteria;
  1756. $criteria->select = 't.*,`city`.`city`, `state`.`state`, `leadSourceMaster`.`leadSourceTitle`,`leadSourceMaster`.`leadSourceCode`,`leadStageMaster`.`leadStage`,`leadStatus`.`leadStatus`, `customerTypeMaster`.`customerType`,`productMaster`.`productName`,`policyTypeMaster`.`policyType`,`planTypeMaster`.`planType`,`campaign`.`campaignName`';
  1757. $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)';
  1758. $criteria->condition='t.status != "Allocated" AND t.leadStatusId != "25" AND t.leadStatusId != "26" ';
  1759. $criteria->order='leadId DESC';
  1760. $model=new LeadReport();
  1761. $model->scenario = 'LeadReport';
  1762. $reportmodel=LeadReport::model()->findAll($criteria);
  1763. $data=array();
  1764. $datas = $reportmodel;
  1765. foreach($datas as $key=>$value){
  1766. $data[$key]=$value;
  1767. }
  1768. if(count($data)>0){
  1769. Yii::import('ext.phpexcel.XPHPExcel');
  1770. $objPHPExcel= XPHPExcel::createPHPExcel();
  1771. $objPHPExcel->getProperties()->setCreator("ReligareLMS")
  1772. ->setLastModifiedBy("ReligareLMS")
  1773. ->setTitle("Office 2007 XLSX Test Document")
  1774. ->setSubject("Office 2007 XLSX Test Document")
  1775. ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
  1776. ->setKeywords("office 2007 openxml php")
  1777. ->setCategory("Test result file");
  1778. $total_excelColumns=$this->getNameFromNumber(8);
  1779. // Rename worksheet
  1780. $objPHPExcel->getActiveSheet()->setTitle('Sample Excel');
  1781. $objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(25);
  1782. $objPHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight(20);
  1783. $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(6);
  1784. $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
  1785. $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
  1786. $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(30);
  1787. $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30);
  1788. $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(30);
  1789. $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(30);
  1790. $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(30);
  1791. $objPHPExcel->getActiveSheet()->duplicateStyleArray(
  1792. array(
  1793. 'font' => array(
  1794. 'name' => 'Times New Roman',
  1795. 'bold' => true,
  1796. 'italic' => false,
  1797. 'size' => 12
  1798. ),
  1799. 'borders' => array(
  1800. 'top' => array('style' => PHPExcel_Style_Border::BORDER_DOUBLE),
  1801. 'bottom' => array('style' => PHPExcel_Style_Border::BORDER_DOUBLE),
  1802. 'left' => array('style' => PHPExcel_Style_Border::BORDER_DOUBLE),
  1803. 'right' => array('style' => PHPExcel_Style_Border::BORDER_DOUBLE)
  1804. ),
  1805. 'alignment' => array(
  1806. 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
  1807. 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
  1808. 'wrap' => true
  1809. )
  1810. ),
  1811. 'A1:'.$total_excelColumns.'1'
  1812. );
  1813. // Set active sheet index to the first sheet, so Excel opens this as the first sheet
  1814. // Add some data
  1815. $objPHPExcel->setActiveSheetIndex(0)
  1816. ->setCellValue('A1', 'SNO.')
  1817. ->setCellValue('B1', 'Name')
  1818. ->setCellValue('C1', 'Mobile')
  1819. ->setCellValue('D1', 'Email')
  1820. ->setCellValue('E1', 'Lead Stage')
  1821. ->setCellValue('F1', 'Date and Time')
  1822. ->setCellValue('G1', 'UTM Code')
  1823. ->setCellValue('H1', 'status');
  1824. // Miscellaneous glyphs, UTF-8
  1825. $i=0;
  1826. $k=2;
  1827. $sn=1;
  1828. while($i<count($data)){
  1829. $objPHPExcel->setActiveSheetIndex(0)
  1830. ->setCellValue('A'.$k,$sn)
  1831. ->setCellValue('B'.$k,$data[$i]['name'])
  1832. ->setCellValue('C'.$k,$data[$i]['mobile'])
  1833. ->setCellValue('D'.$k,$data[$i]['email'])
  1834. ->setCellValue('E'.$k,$data[$i]['leadStage'])
  1835. ->setCellValue('F'.$k,date("d/m/y h:i A",$data[$i]['createdOn']))
  1836. ->setCellValue('G'.$k,$data[$i]['leadSourceCode'])
  1837. ->setCellValue('H'.$k,$data[$i]['status']);
  1838. $i++;$k++;$sn++;}
  1839. // Redirect output to a client�s web browser (Excel5)
  1840. header('Content-Type: application/vnd.ms-excel');
  1841. header('Content-Disposition: attachment;filename="lead_report.xls"');
  1842. header('Cache-Control: max-age=0');
  1843. // If you're serving to IE 9, then the following may be needed
  1844. header('Cache-Control: max-age=1');
  1845. // If you're serving to IE over SSL, then the following may be needed
  1846. header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
  1847. header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
  1848. header ('Pragma: public'); // HTTP/1.0
  1849. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
  1850. $objWriter->save('php://output');
  1851. Yii::app()->end();
  1852. }
  1853. else{
  1854. $model = new Lead();
  1855. $model = Lead::model()->findAll("status = 'Active'");
  1856. $this->render('lead_list',array('model'=>$model));
  1857. }
  1858. }
  1859. public function actiongetSourceResults(){
  1860. $models=new Lead();
  1861. $type=@$_REQUEST['type'];
  1862. $searchTxt=@$_REQUEST['searchTxt'];
  1863. if(isset($searchTxt) && !empty($searchTxt)){
  1864. $this->renderPartial('searchSourceLeads',array('searchTxt'=>$searchTxt,'type'=>@$type));
  1865. } else {
  1866. if($type=='fresh'){
  1867. $functs="fresh_leads";
  1868. }
  1869. if($type=='new'){
  1870. $functs="lead_list";
  1871. }
  1872. if($type=='duplicate'){
  1873. $functs="duplicate_lead_list";
  1874. }
  1875. if($type=='junk'){
  1876. $functs="junk_lead_list";
  1877. }
  1878. if($type=='allocated'){
  1879. $functs="allocated_lead_list";
  1880. }
  1881. if($type=='cip'){
  1882. $functs="cip_lead_list";
  1883. }
  1884. if($type=='plc'){
  1885. $functs="plc_lead_list";
  1886. }
  1887. if($type=='closed'){
  1888. $functs="close_lead_list";
  1889. }
  1890. if($type==''){
  1891. $functs="lead_list";
  1892. }
  1893. echo Yii::app()->createUrl('leads/'.@$functs);
  1894. exit;
  1895. }
  1896. }
  1897. public function actionAutocompleteSearch(){
  1898. $models=new Lead();
  1899. $term=@$_REQUEST['term'];
  1900. $type=@$_REQUEST['type'];
  1901. if($type=="fresh"){
  1902. $models=Lead::model()->findAll(array("condition"=>"leadStatusId = '34' AND currentAllocatedId<1 and concat(name,mobile,email) like '%$term%'","order"=>"leadId desc"));
  1903. }
  1904. if($type=="new"){
  1905. $relationManager = $_SESSION['relationalManager'];
  1906. $managerMemberId = implode(",",array_unique(@$relationManager));
  1907. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  1908. $querycondition = " leadStatusId = '35' AND currentAllocatedId > 0 AND isRead='no' ";
  1909. } else {
  1910. $querycondition = " leadStatusId = '35' AND currentAllocatedId > 0 AND isRead='no' AND currentAllocatedId IN (".@$managerMemberId.") ";
  1911. }
  1912. $models = Lead::model()->findAll(" $querycondition and concat(name,mobile,email) like '%$term%'");
  1913. //$models=Lead::model()->findAll(array("condition"=>"leadStatusId = '34' AND currentAllocatedId<1 and name like '%$term%'","order"=>"leadId desc"));
  1914. }
  1915. if($type=="duplicate"){
  1916. $models=Lead::model()->findAll(array("condition"=>"leadStatusId = '10' and concat(name,mobile,email) like '%$term%'","order"=>"leadId desc"));
  1917. }
  1918. if($type=="dupforday"){
  1919. $today12PM = mktime(0,0,0,date("m"),date("d"),date("Y"));
  1920. $models=Lead::model()->findAll(array("condition"=>"leadStatusId = '10' AND createdOn > '".@$today12PM."' and concat(name,mobile,email) like '%$term%'","order"=>"leadId desc"));
  1921. }
  1922. if($type=="junk"){
  1923. $models=Lead::model()->findAll(array("condition"=>"leadStatusId = '36' and concat(name,mobile,email) like '%$term%'","order"=>"leadId desc"));
  1924. }
  1925. if($type=="allocated"){
  1926. $relationManager = $_SESSION['relationalManager'];
  1927. $managerMemberId = implode(",",array_unique(@$relationManager));
  1928. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  1929. $querycondition = " currentAllocatedId>0 AND isRead = 'yes'";
  1930. } else {
  1931. $querycondition = " currentAllocatedId>0 AND isRead = 'yes' AND currentAllocatedId IN (".@$managerMemberId.") ";
  1932. }
  1933. $models = Lead::model()->findAll(" $querycondition and concat(name,mobile,email) like '%$term%'");
  1934. }
  1935. if($type=="followup"){
  1936. $today12PM = mktime(0,0,0,date("m"),date("d"),date("Y"));
  1937. $relationManager = $_SESSION['relationalManager'];
  1938. $managerMemberId = implode(",",array_unique(@$relationManager));
  1939. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  1940. $querycondition = ' startDate = "'.@$today12PM.'" and status="Pending" ';
  1941. } else {
  1942. $querycondition = " startDate = '".@$starttimestamp."' AND status = 'Pending' AND userId IN (".@$managerMemberId.") ";
  1943. }
  1944. $models = LeadFollowup::model()->findAll(" $querycondition and description like '%$term%'");
  1945. }
  1946. if($type=="allfollowup"){
  1947. $relationManager = $_SESSION['relationalManager'];
  1948. $managerMemberId = implode(",",array_unique(@$relationManager));
  1949. $currentDate=date('d-m-Y',time());
  1950. $starttimestamp=strtotime($currentDate);
  1951. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  1952. $querycondition = ' status="Pending" ';
  1953. } else {
  1954. $querycondition = " status = 'Pending' AND userId IN (".@$managerMemberId.") ";
  1955. }
  1956. $models = LeadFollowup::model()->findAll(" $querycondition and description like '%$term%'");
  1957. }
  1958. if($type=="closed"){
  1959. $relationManager = $_SESSION['relationalManager'];
  1960. $managerMemberId = implode(",",array_unique(@$relationManager));
  1961. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  1962. $querycondition = "leadStatusId = '7'";
  1963. } else {
  1964. $querycondition = " leadStatusId = '7' AND currentAllocatedId IN (".@$managerMemberId.") ";
  1965. }
  1966. $models = Lead::model()->with("leadSourceDetails")->findAll(" $querycondition and concat(name,mobile,email) like '%$term%' ");
  1967. }
  1968. if($type=="cip"){
  1969. $contactInProgList=Yii::app()->db->createCommand("select leadStatus.leadStatus,leadStatusId from leadStatus where parentId=3")->queryAll();
  1970. $CIPids = array();
  1971. if(count($contactInProgList) > 0){
  1972. for($w=0;$w<count($contactInProgList);$w++){
  1973. @$CIPids[] = @$contactInProgList[$w]['leadStatusId'];
  1974. }
  1975. } else {
  1976. @$CIPids[] = '';
  1977. }
  1978. @$CIPids = implode(",",@$CIPids);
  1979. $relationManager = $_SESSION['relationalManager'];
  1980. $managerMemberId = implode(",",array_unique(@$relationManager));
  1981. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  1982. $querycondition = " leadStatusId IN ( ".@$CIPids." ) ";
  1983. } else {
  1984. $querycondition = " leadStatusId IN ( ".@$CIPids." ) AND currentAllocatedId IN (".@$managerMemberId.") ";
  1985. }
  1986. $models = Lead::model()->findAll(" $querycondition and concat(name,mobile,email) like '%$term%'");
  1987. }
  1988. if($type=="plc"){
  1989. $contactInProgList=Yii::app()->db->createCommand("select leadStatus.leadStatus,leadStatusId from leadStatus where parentId=41")->queryAll();
  1990. $CIPids = array();
  1991. if(count($contactInProgList) > 0){
  1992. for($w=0;$w<count($contactInProgList);$w++){
  1993. @$CIPids[] = @$contactInProgList[$w]['leadStatusId'];
  1994. }
  1995. } else {
  1996. @$CIPids[] = '';
  1997. }
  1998. @$CIPids = implode(",",@$CIPids);
  1999. $relationManager = $_SESSION['relationalManager'];
  2000. $managerMemberId = implode(",",array_unique(@$relationManager));
  2001. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  2002. $querycondition = " leadStatusId IN ( ".@$CIPids." ) ";
  2003. } else {
  2004. $querycondition = " leadStatusId IN ( ".@$CIPids." ) AND currentAllocatedId IN (".@$managerMemberId.") ";
  2005. }
  2006. $models = Lead::model()->findAll(" $querycondition and concat(name,mobile,email) like '%$term%'");
  2007. }
  2008. if($type=="cld"){
  2009. $today12PM = mktime(0,0,0,date("m"),date("d"),date("Y"));
  2010. $relationManager = $_SESSION['relationalManager'];
  2011. $managerMemberId = implode(",",array_unique(@$relationManager));
  2012. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  2013. $querycondition = 'leadStatusId = 12 AND startDate = "'.@$today12PM.'" ';
  2014. } else {
  2015. $querycondition = "leadStatusId = 12 AND startDate = '".@$today12PM."' AND userId IN (".@$managerMemberId.") ";
  2016. }
  2017. $models = LeadFollowup::model()->findAll(" $querycondition and description like '%$term%'");
  2018. }
  2019. if($type=="followup" or $type=="allfollowup" or $type=="cld"){
  2020. $arr = array();
  2021. foreach($models as $model) {
  2022. $arr[] = array(
  2023. 'label'=>substr($model->description,0,10), // label for dropdown list
  2024. 'value'=>substr($model->description,0,10), // value for input field
  2025. 'id'=>$model->leadFollowupId, // return value from autocomplete
  2026. );
  2027. }
  2028. if(count($models) > 0){
  2029. $arr['totalRecords'] = array(
  2030. 'totalRecords'=>count($models), // return value from autocomplete
  2031. );
  2032. }
  2033. }else {
  2034. $arr = array();
  2035. foreach($models as $model) {
  2036. $arr[] = array(
  2037. 'label'=>$model->mobile?$model->mobile.($model->name?'/'.$model->name:'').($model->email?'/'.$model->email:''):'', // label for dropdown list
  2038. 'value'=>$model->mobile?$model->mobile:$model->name, // value for input field
  2039. 'id'=>$model->leadId, // return value from autocomplete
  2040. );
  2041. }
  2042. if(count($models) > 0){
  2043. $arr['totalRecords'] = array(
  2044. 'totalRecords'=>count($models), // return value from autocomplete
  2045. );
  2046. }
  2047. }
  2048. echo CJSON::encode($arr);
  2049. Yii::app()->end();
  2050. //$this->renderPartial('searchLeads');
  2051. }
  2052. public function actionAutocompleteSearchSource(){
  2053. $models=new Lead();
  2054. $term=@$_REQUEST['term'];
  2055. $type=@$_REQUEST['type'];
  2056. if($type=="fresh"){
  2057. $models=Lead::model()->with("leadSourceDetails")->findAll(array("condition"=>"leadStatusId = '34' AND currentAllocatedId<1 and concat(leadSourceTitle) like '%$term%'","order"=>"leadId desc"));
  2058. }
  2059. if($type=="new"){
  2060. $relationManager = $_SESSION['relationalManager'];
  2061. $managerMemberId = implode(",",array_unique(@$relationManager));
  2062. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  2063. $querycondition = " leadStatusId = '35' AND currentAllocatedId > 0 AND isRead='no' ";
  2064. } else {
  2065. $querycondition = " leadStatusId = '35' AND currentAllocatedId > 0 AND isRead='no' AND currentAllocatedId IN (".@$managerMemberId.") ";
  2066. }
  2067. $models = Lead::model()->with("leadSourceDetails")->findAll(" $querycondition and leadSourceTitle like '%$term%'");
  2068. //$models=Lead::model()->findAll(array("condition"=>"leadStatusId = '34' AND currentAllocatedId<1 and name like '%$term%'","order"=>"leadId desc"));
  2069. }
  2070. if($type=="duplicate"){
  2071. $models=Lead::model()->with("leadSourceDetails")->findAll(array("condition"=>"leadStatusId = '10' and leadSourceTitle like '%$term%'","order"=>"leadId desc"));
  2072. }
  2073. if($type=="junk"){
  2074. $models=Lead::model()->with("leadSourceDetails")->findAll(array("condition"=>"leadStatusId = '36' and leadSourceTitle like '%$term%'","order"=>"leadId desc"));
  2075. }
  2076. if($type=="allocated"){
  2077. $relationManager = $_SESSION['relationalManager'];
  2078. $managerMemberId = implode(",",array_unique(@$relationManager));
  2079. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  2080. $querycondition = " currentAllocatedId>0 AND isRead = 'yes'";
  2081. } else {
  2082. $querycondition = " currentAllocatedId>0 AND isRead = 'yes' AND currentAllocatedId IN (".@$managerMemberId.") ";
  2083. }
  2084. $models = Lead::model()->with("leadSourceDetails")->findAll(" $querycondition and leadSourceTitle like '%$term%'");
  2085. }
  2086. if($type=="followup"){
  2087. $today12PM = mktime(0,0,0,date("m"),date("d"),date("Y"));
  2088. $relationManager = $_SESSION['relationalManager'];
  2089. $managerMemberId = implode(",",array_unique(@$relationManager));
  2090. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  2091. $querycondition = ' startDate = "'.@$today12PM.'" and status="Pending" ';
  2092. } else {
  2093. $querycondition = " startDate = '".@$starttimestamp."' AND status = 'Pending' AND userId IN (".@$managerMemberId.") ";
  2094. }
  2095. $models = LeadFollowup::model()->findAll(" $querycondition and description leadSourceTitle '%$term%'");
  2096. }
  2097. if($type=="closed"){
  2098. $today12PM = mktime(0,0,0,date("m"),date("d"),date("Y"));
  2099. $relationManager = $_SESSION['relationalManager'];
  2100. $managerMemberId = implode(",",array_unique(@$relationManager));
  2101. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  2102. $querycondition = "leadStatusId = '7'";
  2103. } else {
  2104. $querycondition = " leadStatusId = '7' AND currentAllocatedId IN (".@$managerMemberId.") ";
  2105. }
  2106. $models = Lead::model()->with("leadSourceDetails")->findAll(" $querycondition and leadSourceTitle like '%$term%' ");
  2107. }
  2108. if($type=="followup"){
  2109. $arr = array();
  2110. foreach($models as $model) {
  2111. $arr[] = array(
  2112. 'label'=>substr($model->description,0,10), // label for dropdown list
  2113. 'value'=>substr($model->description,0,10), // value for input field
  2114. 'id'=>$model->leadFollowupId, // return value from autocomplete
  2115. );
  2116. }
  2117. if(count($models) > 0){
  2118. $arr['totalRecords'] = array(
  2119. 'totalRecords'=>count($models), // return value from autocomplete
  2120. );
  2121. }
  2122. }else {
  2123. $arr = array();
  2124. foreach($models as $model) {
  2125. $arr[] = array(
  2126. 'label'=>$model->mobile?$model->mobile:$model->name, // label for dropdown list
  2127. 'value'=>$model->mobile?$model->mobile:$model->name, // value for input field
  2128. 'id'=>$model->leadId, // return value from autocomplete
  2129. );
  2130. }
  2131. if(count($models) > 0){
  2132. $arr['totalRecords'] = array(
  2133. 'totalRecords'=>count($models), // return value from autocomplete
  2134. );
  2135. }
  2136. }
  2137. echo CJSON::encode($arr);
  2138. Yii::app()->end();
  2139. //$this->renderPartial('searchLeads');
  2140. }
  2141. public function actionAutocompleteSearchRes(){
  2142. $models=new Lead();
  2143. $term=@$_REQUEST['id'];
  2144. $type=@$_REQUEST['type'];
  2145. $models=Lead::model()->findAll(array("condition"=>"leadStatusId = '34' AND currentAllocatedId<1 and name like '%$term%'","order"=>"leadId desc"));
  2146. $arr = array();
  2147. $this->renderPartial('searchLeads',array('name'=>$term));
  2148. }
  2149. public function actionexportArchiveList(){
  2150. $Leadname = @$_REQUEST['name'];
  2151. $Leadstatus = @$_REQUEST['status'];
  2152. $leadStage = @$_REQUEST['statge'];
  2153. $cond ='';
  2154. if(isset($Leadname) && !empty($Leadname)){
  2155. $cond .=" AND name like '%".@$Leadname."%'";
  2156. }
  2157. if(isset($Leadstatus) && !empty($Leadstatus)){
  2158. $cond .=" AND leadStatusId = '".@$Leadstatus."'";
  2159. }
  2160. if(isset($leadStage) && !empty($leadStage)){
  2161. $cond .=" AND leadStageId = '".@$leadStage."'";
  2162. }
  2163. $dataProvider = new CActiveDataProvider('Lead', array('criteria'=>array(
  2164. 'condition'=>' FROM_UNIXTIME(updatedOn) >= DATE_SUB(CURDATE(), INTERVAL 120 DAY) '.@$cond.' and leadStatusId NOT IN (12,8,1,4) ',
  2165. 'order'=>'',
  2166. )));
  2167. $iterator = new CDataProviderIterator($dataProvider);
  2168. $data=array();
  2169. $datas = $iterator;
  2170. foreach($datas as $key=>$value){
  2171. $data[$key]=$value;
  2172. }
  2173. Yii::import('ext.phpexcel.XPHPExcel');
  2174. $objPHPExcel= XPHPExcel::createPHPExcel();
  2175. $objPHPExcel->getProperties()->setCreator("ReligareLMS")
  2176. ->setLastModifiedBy("ReligareLMS")
  2177. ->setTitle("Office 2007 XLSX Leads Document")
  2178. ->setSubject("Office 2007 XLSX Leads Document")
  2179. ->setDescription("Archive Leads.")
  2180. ->setKeywords("Archive Leads")
  2181. ->setCategory("Archive Leads");
  2182. // Rename worksheet
  2183. $objPHPExcel->getActiveSheet()->setTitle('Sample Excel');
  2184. $objPHPExcel->getActiveSheet()->getRowDimension(1)->setRowHeight(25);
  2185. $objPHPExcel->getActiveSheet()->getRowDimension(2)->setRowHeight(20);
  2186. $objPHPExcel->getActiveSheet()->getColumnDimension('A')->setWidth(6);
  2187. $objPHPExcel->getActiveSheet()->getColumnDimension('B')->setWidth(30);
  2188. $objPHPExcel->getActiveSheet()->getColumnDimension('C')->setWidth(30);
  2189. $objPHPExcel->getActiveSheet()->getColumnDimension('D')->setWidth(30);
  2190. $objPHPExcel->getActiveSheet()->getColumnDimension('E')->setWidth(30);
  2191. $objPHPExcel->getActiveSheet()->getColumnDimension('F')->setWidth(30);
  2192. $objPHPExcel->getActiveSheet()->getColumnDimension('G')->setWidth(30);
  2193. $objPHPExcel->getActiveSheet()->getColumnDimension('H')->setWidth(30);
  2194. $objPHPExcel->getActiveSheet()->getColumnDimension('I')->setWidth(30);
  2195. $objPHPExcel->getActiveSheet()->getColumnDimension('J')->setWidth(30);
  2196. $objPHPExcel->getActiveSheet()->getColumnDimension('K')->setWidth(30);
  2197. $objPHPExcel->getActiveSheet()->getColumnDimension('L')->setWidth(30);
  2198. $objPHPExcel->getActiveSheet()->getColumnDimension('M')->setWidth(30);
  2199. $objPHPExcel->getActiveSheet()->getColumnDimension('N')->setWidth(30);
  2200. $objPHPExcel->getActiveSheet()->getColumnDimension('O')->setWidth(30);
  2201. $objPHPExcel->getActiveSheet()->getColumnDimension('P')->setWidth(30);
  2202. $objPHPExcel->getActiveSheet()->getColumnDimension('Q')->setWidth(30);
  2203. $objPHPExcel->getActiveSheet()->getColumnDimension('R')->setWidth(30);
  2204. $objPHPExcel->getActiveSheet()->getColumnDimension('S')->setWidth(30);
  2205. $objPHPExcel->getActiveSheet()->getColumnDimension('T')->setWidth(30);
  2206. $objPHPExcel->getActiveSheet()->getColumnDimension('U')->setWidth(30);
  2207. $objPHPExcel->getActiveSheet()->getColumnDimension('V')->setWidth(30);
  2208. $objPHPExcel->getActiveSheet()->getColumnDimension('W')->setWidth(30);
  2209. $objPHPExcel->getActiveSheet()->getColumnDimension('X')->setWidth(30);
  2210. $objPHPExcel->getActiveSheet()->getColumnDimension('y')->setWidth(30);
  2211. $objPHPExcel->getActiveSheet()->duplicateStyleArray(
  2212. array(
  2213. 'font' => array(
  2214. 'name' => 'Times New Roman',
  2215. 'bold' => true,
  2216. 'italic' => false,
  2217. 'size' => 12
  2218. ),
  2219. 'borders' => array(
  2220. 'top' => array('style' => PHPExcel_Style_Border::BORDER_DOUBLE),
  2221. 'bottom' => array('style' => PHPExcel_Style_Border::BORDER_DOUBLE),
  2222. 'left' => array('style' => PHPExcel_Style_Border::BORDER_DOUBLE),
  2223. 'right' => array('style' => PHPExcel_Style_Border::BORDER_DOUBLE)
  2224. ),
  2225. 'alignment' => array(
  2226. 'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
  2227. 'vertical' => PHPExcel_Style_Alignment::VERTICAL_CENTER,
  2228. 'wrap' => true
  2229. )
  2230. ),
  2231. 'A1:Y1'
  2232. );
  2233. // Set active sheet index to the first sheet, so Excel opens this as the first sheet
  2234. // Add some data
  2235. $objPHPExcel->setActiveSheetIndex(0)
  2236. ->setCellValue('A1', 'SNO.')
  2237. ->setCellValue('B1', 'Name')
  2238. ->setCellValue('C1', 'Mobile Number')
  2239. ->setCellValue('D1', 'Email Id')
  2240. ->setCellValue('E1', 'Address')
  2241. ->setCellValue('F1', 'City')
  2242. ->setCellValue('G1', 'State')
  2243. ->setCellValue('H1', 'Members')
  2244. ->setCellValue('I1', 'Premium')
  2245. ->setCellValue('J1', 'Product Details')
  2246. ->setCellValue('K1', 'Lead Status')
  2247. ->setCellValue('L1', 'Status')
  2248. ->setCellValue('M1', 'isJunk')
  2249. ->setCellValue('N1', 'Lead Source')
  2250. ->setCellValue('O1', 'Lead Stage')
  2251. ->setCellValue('P1', 'Lead Description')
  2252. ->setCellValue('Q1', 'Activity Description')
  2253. ->setCellValue('R1', 'Customer Type')
  2254. ->setCellValue('S1', 'Product Name')
  2255. ->setCellValue('T1', 'Policy Type')
  2256. ->setCellValue('U1', 'Plan Type')
  2257. ->setCellValue('V1', 'Campaign Name')
  2258. ->setCellValue('W1', 'UTM Code')
  2259. ->setCellValue('X1', 'Owner')
  2260. ->setCellValue('Y1', 'Last Modified Date');
  2261. // Miscellaneous glyphs, UTF-8
  2262. $i=0;
  2263. $k=2;
  2264. $sn=1;
  2265. while($i<count($data)){
  2266. $str = preg_replace('/\s\s+/', ' ', $data[$i]['address']);
  2267. if($data[$i]['currentAllocatedId']==$data[$i]['createdBy']){
  2268. $owner = $data[$i]['ownerDetails']['firstName']." ".$data[$i]['ownerDetails']['lastName']."(C)";
  2269. } else {
  2270. if(isset($data[$i]['ownerDetails']['firstName']) && !empty($data[$i]['ownerDetails']['firstName'])){
  2271. $owner = $data[$i]['ownerDetails']['firstName']." ".$data[$i]['ownerDetails']['lastName'];
  2272. } else {
  2273. $owner = "NA";
  2274. }
  2275. }
  2276. $descrecords=Yii::app()->db->createCommand("select leadDescription from lead where leadId='".@$data[$i]['leadId']."' ")->queryAll();
  2277. $records=Yii::app()->db->createCommand("select description from leadFollowup where leadId='".@$data[$i]['leadId']."' ")->queryAll();
  2278. $ActivityRes = '';
  2279. for($j=0;$j<count($records);$j++){
  2280. @$ActivityRes .= @$records[0]['description'].",";
  2281. }
  2282. $lastModifieddate = date("d M Y H:i:s A",$data[$i]['updatedOn']);
  2283. //ReportsController::getLeadDescription(@$data->leadId);
  2284. //$data[$i]['ownerDetails']['firstName'];
  2285. $objPHPExcel->setActiveSheetIndex(0)
  2286. ->setCellValue('A'.$k,$sn)
  2287. ->setCellValue('B'.$k,$data[$i]['name'])
  2288. ->setCellValue('C'.$k,$data[$i]['mobile'])
  2289. ->setCellValue('D'.$k,$data[$i]['email'])
  2290. ->setCellValue('E'.$k,$str)
  2291. ->setCellValue('F'.$k,$data[$i]['city'])
  2292. ->setCellValue('G'.$k,$data[$i]['state'])
  2293. ->setCellValue('H'.$k,$data[$i]['members'])
  2294. ->setCellValue('I'.$k,$data[$i]['premium'])
  2295. ->setCellValue('J'.$k,$data[$i]['productDetails'])
  2296. ->setCellValue('K'.$k,$data[$i]['leadStatusDetails']['leadStatus'])
  2297. ->setCellValue('L'.$k,$data[$i]['status'])
  2298. ->setCellValue('M'.$k,$data[$i]['isJunk'])
  2299. ->setCellValue('N'.$k,$data[$i]['leadSourceTitle'])
  2300. ->setCellValue('O'.$k,$data[$i]['leadStage'])
  2301. ->setCellValue('P'.$k,@$descrecords[0]['leadDescription'])
  2302. ->setCellValue('Q'.$k,@$ActivityRes)
  2303. ->setCellValue('R'.$k,$data[$i]['customerType'])
  2304. ->setCellValue('S'.$k,$data[$i]['productName'])
  2305. ->setCellValue('T'.$k,$data[$i]['policyType'])
  2306. ->setCellValue('U'.$k,$data[$i]['planType'])
  2307. ->setCellValue('V'.$k,$data[$i]['campaignName'])
  2308. ->setCellValue('W'.$k,$data[$i]['leadSourceCode'])
  2309. ->setCellValue('X'.$k,$owner)
  2310. ->setCellValue('Y'.$k,$lastModifieddate);
  2311. $i++;$k++;$sn++;}
  2312. // Redirect output to a client�s web browser (Excel5)
  2313. header('Content-Type: application/vnd.ms-excel');
  2314. header('Content-Disposition: attachment;filename="lead_report.xls"');
  2315. header('Cache-Control: max-age=0');
  2316. // If you're serving to IE 9, then the following may be needed
  2317. header('Cache-Control: max-age=1');
  2318. // If you're serving to IE over SSL, then the following may be needed
  2319. header ('Last-Modified: '.gmdate('D, d M Y H:i:s').' GMT'); // always modified
  2320. header ('Cache-Control: cache, must-revalidate'); // HTTP/1.1
  2321. header ('Pragma: public'); // HTTP/1.0
  2322. $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
  2323. $objWriter->save('php://output');
  2324. Yii::app()->end();
  2325. }
  2326. public function actiongetCityList()
  2327. {
  2328. $data=City::model()->findAll(array('condition'=>'stateId=:stateId and status=:status','params'=>array(':stateId'=>(int) $_POST['stateId'],'status'=>'Active')));
  2329. $data=CHtml::listData($data,'cityId','city');
  2330. echo '<select class="styled" name="Lead[cityId]" style="position: absolute; opacity: 0; font-size: 12px; height: 25px;" onchange="changeText();">';
  2331. echo '<option value="" selected="selected">Select City</option>';
  2332. foreach($data as $value=>$name)
  2333. {
  2334. echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name));
  2335. }
  2336. echo '</select>';
  2337. echo '<span id="changeText" class="customStyleSelectBox" style="display: block;width:97px;"><span class="customStyleSelectBoxInner" style="width: 81px; display: block;">Select City</span></span>';
  2338. }
  2339. public function actiongetLeadStatus()
  2340. {
  2341. if(isset($_POST['parentId']) && !empty($_POST['parentId'])){
  2342. $data=LeadStatus::model()->findAll(array('condition'=>'parentId=:parentId and status=:status','params'=>array(':parentId'=>(int) @$_POST['parentId'],'status'=>'Active')));
  2343. $data=CHtml::listData($data,'leadStatusId','leadStatus');
  2344. echo '<select class="styled" name="Lead[leadStatusId]" style="position: absolute; opacity: 0; font-size: 12px; height: 25px;" id="leadprimarystatus" onchange="changeStatusText();getActionRes(this.value);">';
  2345. echo '<option value="" selected="selected">Select lead Status</option>';
  2346. foreach($data as $value=>$name)
  2347. {
  2348. echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name));
  2349. }
  2350. echo '</select>';
  2351. } else {
  2352. echo '<select class="styled" name="Lead[leadStatusId]" style="position: absolute; opacity: 0; font-size: 12px; height: 25px;" id="leadprimarystatus" onchange="changeStatusText();getActionRes(this.value);">';
  2353. echo '<option value="" selected="selected">Select lead Status</option>';
  2354. echo '</select>';
  2355. }
  2356. echo '<span id="changeStatusText" class="customStyleSelectBox" style="display: block;min-width:142px;"><span class="customStyleSelectBoxInner" style="width: 81px; display: block;">Select lead Status</span></span>';
  2357. }
  2358. public function actionexportLeads(){
  2359. $model=new Lead();
  2360. $type=@$_REQUEST['type'];
  2361. $relationManager = @$_SESSION['relationalManager'];
  2362. $managerMemberId = implode(",",array_unique(@$relationManager));
  2363. $today12PM = mktime(0,0,0,date("m"),date("d"),date("Y"));
  2364. if($type=="freshLeads"){
  2365. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  2366. $querycondition = " leadStatusId = '34' AND currentAllocatedId<1";
  2367. } else {
  2368. $querycondition = " leadStatusId = '34' AND currentAllocatedId<1";
  2369. }
  2370. $dataProvider=new CActiveDataProvider('Lead', array('criteria'=>array(
  2371. 'condition'=>@$querycondition,
  2372. 'order'=>'leadId DESC',
  2373. ),
  2374. 'pagination'=>false,
  2375. ));
  2376. }
  2377. if($type=="newLeads"){
  2378. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  2379. $querycondition = " leadStatusId = '35' AND currentAllocatedId > 0 AND isRead = 'no' ";
  2380. } else {
  2381. $querycondition = " leadStatusId = '35' AND currentAllocatedId > 0 AND isRead = 'no' AND currentAllocatedId IN (".@$managerMemberId.") ";
  2382. }
  2383. $dataProvider=new CActiveDataProvider('Lead', array('criteria'=>array(
  2384. 'condition'=>@$querycondition,
  2385. 'order'=>'leadId DESC',
  2386. ),
  2387. 'pagination'=>array(
  2388. 'pageSize'=> 10,
  2389. ),
  2390. ));
  2391. }
  2392. if($type=="allocatedLeads"){
  2393. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  2394. $queryCondition = " currentAllocatedId>0 AND isRead = 'yes' ";
  2395. } else {
  2396. $queryCondition = " currentAllocatedId>0 AND isRead = 'yes' AND currentAllocatedId IN (".@$managerMemberId.") ";
  2397. }
  2398. $dataProvider=new CActiveDataProvider('Lead', array('criteria'=>array(
  2399. 'condition'=>@$queryCondition,
  2400. 'order'=>'leadId DESC',
  2401. )));
  2402. }
  2403. if($type=="Allfollowup"){
  2404. $currentDate=date('d-m-Y',time());
  2405. $starttimestamp=strtotime($currentDate);
  2406. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  2407. $queryCondition = ' status="Pending" and userId = "'.@$_SESSION['id'].'" ';
  2408. } else {
  2409. $queryCondition = " status = 'Pending' AND userId IN (".@$managerMemberId.") ";
  2410. }
  2411. $dataProvider=new CActiveDataProvider('LeadFollowup', array('criteria'=>array(
  2412. 'condition'=>@$queryCondition,
  2413. 'order'=>'leadFollowupId DESC',
  2414. )));
  2415. }
  2416. if($type=="followupLeads"){
  2417. $currentDate=date('d-m-Y',time());
  2418. $starttimestamp=strtotime($currentDate);
  2419. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  2420. $queryCondition = ' startDate = "'.@$starttimestamp.'" and status="Pending" and userId = "'.@$_SESSION['id'].'" ';
  2421. } else {
  2422. $queryCondition = " startDate = '".@$starttimestamp."' AND status = 'Pending' AND userId IN (".@$managerMemberId.") ";
  2423. }
  2424. $dataProvider=new CActiveDataProvider('LeadFollowup', array('criteria'=>array(
  2425. 'condition'=>@$queryCondition,
  2426. 'order'=>'leadFollowupId DESC',
  2427. )));
  2428. }
  2429. if($type=="duplicateLeads"){
  2430. $dataProvider=new CActiveDataProvider('Lead', array('criteria'=>array(
  2431. 'condition'=>' leadStatusId = "10" ',
  2432. 'order'=>'leadId DESC',
  2433. )));
  2434. }
  2435. if($type=="dupforday"){
  2436. $today12PM = mktime(0,0,0,date("m"),date("d"),date("Y"));
  2437. $dataProvider=new CActiveDataProvider('Lead', array('criteria'=>array(
  2438. 'condition'=>' leadStatusId = "10" AND createdOn > "'.@$today12PM.'" ',
  2439. 'order'=>'leadId DESC',
  2440. )));
  2441. }
  2442. if($type=="junkLeads"){
  2443. $dataProvider=new CActiveDataProvider('Lead', array('criteria'=>array(
  2444. 'condition'=>' leadStatusId = "36" ',
  2445. 'order'=>'leadId DESC',
  2446. )));
  2447. }
  2448. if($type=="closeLeads"){
  2449. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  2450. $querycondition = "leadStatusId = '7' ";
  2451. } else {
  2452. $querycondition = " leadStatusId = '7' AND currentAllocatedId IN (".@$managerMemberId.") ";
  2453. }
  2454. $dataProvider=new CActiveDataProvider('Lead', array('criteria'=>array(
  2455. 'condition'=>@$querycondition,
  2456. 'order'=>'leadId desc',
  2457. ),
  2458. ));
  2459. }
  2460. if($type=="cip"){
  2461. $contactInProgList=Yii::app()->db->createCommand("select leadStatus.leadStatus,leadStatusId from leadStatus where parentId=3")->queryAll();
  2462. $CIPids = array();
  2463. if(count($contactInProgList) > 0){
  2464. for($w=0;$w<count($contactInProgList);$w++){
  2465. @$CIPids[] = @$contactInProgList[$w]['leadStatusId'];
  2466. }
  2467. } else {
  2468. @$CIPids[] = '';
  2469. }
  2470. @$CIPids = implode(",",@$CIPids);
  2471. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  2472. $querycondition = "leadStatusId IN ( ".@$CIPids." ) ";
  2473. } else {
  2474. $querycondition = " leadStatusId IN ( ".@$CIPids." ) AND currentAllocatedId IN (".@$managerMemberId.") ";
  2475. }
  2476. $dataProvider=new CActiveDataProvider('Lead', array('criteria'=>array(
  2477. 'condition'=>@$querycondition,
  2478. 'order'=>'leadId desc',
  2479. ),
  2480. 'pagination'=>false,
  2481. ));
  2482. }
  2483. if($type=="plc"){
  2484. $contactInProgList=Yii::app()->db->createCommand("select leadStatus.leadStatus,leadStatusId from leadStatus where parentId=41")->queryAll();
  2485. $CIPids = array();
  2486. if(count($contactInProgList) > 0){
  2487. for($w=0;$w<count($contactInProgList);$w++){
  2488. @$CIPids[] = @$contactInProgList[$w]['leadStatusId'];
  2489. }
  2490. } else {
  2491. @$CIPids[] = '';
  2492. }
  2493. @$CIPids = implode(",",@$CIPids);
  2494. if(@$_SESSION['isAllocator']=='yes' or Yii::app()->session->get('type')=='superadmin') {
  2495. $querycondition = "leadStatusId IN ( ".@$CIPids." )";
  2496. } else {
  2497. $querycondition = " leadStatusId IN ( ".@$CIPids." ) AND currentAllocatedId IN (".@$managerMemberId.") ";
  2498. }
  2499. $dataProvider=new CActiveDataProvider('Lead', array('criteria'=>array(
  2500. 'condition'=>@$querycondition,
  2501. 'order'=>'leadId desc',
  2502. ),
  2503. 'pagination'=>false,
  2504. ));
  2505. }
  2506. $dataProvider->getTotalItemCount($dataProvider);
  2507. if($type=="followupLeads" or $type=="Allfollowup"){
  2508. $iterator = new CDataProviderIterator($dataProvider);
  2509. $file_name = "lms" . "_" . date("Y-m-d_H-i", time()) . ".csv";
  2510. header('Content-Type: text/html; charset=utf-8');
  2511. header("Content-type: application/octet-stream");
  2512. header("Content-Disposition: attachment; filename=\"$file_name\"");
  2513. header("Cache-Control: cache, must-revalidate");
  2514. header("Pragma: public");
  2515. $col = array(
  2516. 'SNO.','Name','Mobile','AgentId','Lead Desciption','Activity Desciption','Email','Action Type','Date and Time','Description','Owner');
  2517. foreach ($col as $key => $value) {
  2518. echo $value . ",";
  2519. }
  2520. echo "\n";
  2521. $i=1;
  2522. foreach($iterator as $data) {
  2523. echo $i++ . ",";
  2524. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$data->leadDetails->name)) . ",";
  2525. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$data->leadDetails->mobile)) . ",";
  2526. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$data->leadDetails->ws_agentid)) . ",";
  2527. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$data->leadDetails->leadDescription)) . ",";
  2528. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$data->description)) . ",";
  2529. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$data->leadDetails->email)) . ",";
  2530. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$data->actionType)) . ",";
  2531. echo date("d/m/y h:i A",$data->createdOn) . ",";
  2532. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$data->description)) . ",";
  2533. echo (@$data->userId==@$data->leadDetails->createdBy)?@$data->ownerDetails->firstName." ".@$data->ownerDetails->lastName."(C)":(@$data->ownerDetails->firstName?@$data->ownerDetails->firstName." ".@$data->ownerDetails->lastName:"NA") . ",";
  2534. echo "\n";
  2535. }
  2536. } else {
  2537. $iterator = new CDataProviderIterator($dataProvider);
  2538. $file_name = "lms" . "_" . date("Y-m-d_H-i", time()) . ".csv";
  2539. header('Content-Type: text/html; charset=utf-8');
  2540. header("Content-type: application/octet-stream");
  2541. header("Content-Disposition: attachment; filename=\"$file_name\"");
  2542. header("Cache-Control: cache, must-revalidate");
  2543. header("Pragma: public");
  2544. $col = array(
  2545. 'SNO.','Name','Mobile','AgentId','Lead Desciption','Activity Desciption','Email','Lead Stage','Date and Time','Lead Status','Owner','status');
  2546. foreach ($col as $key => $value) {
  2547. echo $value . ",";
  2548. }
  2549. echo "\n";
  2550. $i=1;
  2551. foreach($iterator as $data) {
  2552. $sqlDesc = "select group_concat(description) as ActivityDescription from leadFollowup where leadId=".@$data->leadId." ";
  2553. $dataDesc=Yii::app()->db->createCommand($sqlDesc)->queryAll();
  2554. $leadActivity = @$dataDesc[0]['ActivityDescription']?@$dataDesc[0]['ActivityDescription']:'';
  2555. echo $i++ . ",";
  2556. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$data->name)) . ",";
  2557. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$data->mobile)) . ",";
  2558. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$data->ws_agentid)) . ",";
  2559. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$data->leadDescription)) . ",";
  2560. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$leadActivity)) . ",";
  2561. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$data->email)) . ",";
  2562. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$data['leadStageDetails']['leadStage'])) . ",";
  2563. echo date("d/m/y h:i A",$data->createdOn) . ",";
  2564. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$data->leadStatusDetails->leadStatus)) . ",";
  2565. echo (@$data->currentAllocatedId==@$data->createdBy)?@$data->ownerDetails->firstName." ".@$data->ownerDetails->lastName."(C)":(@$data->ownerDetails->firstName?@$data->ownerDetails->firstName." ".@$data->ownerDetails->lastName:"NA") . ",";
  2566. echo "\n";
  2567. }
  2568. }
  2569. }
  2570. public function actionapiPremimum()
  2571. {
  2572. $model = new Lead();
  2573. global $INDIVIDUAL,$FAMILYFLOATER,$GroupCareArray;
  2574. $INDIVIDUAL = array(
  2575. "200000" => "001",
  2576. "300000" => "003",
  2577. "400000" => "005",
  2578. "500000" => "007",
  2579. "700000" => "009",
  2580. "1000000" => "011",
  2581. "1500000" => "013",
  2582. "2000000" => "015",
  2583. "2500000" => "017",
  2584. "5000000" => "019",
  2585. "6000000" => "021"
  2586. );
  2587. $FAMILYFLOATER = array(
  2588. "200000" => "002",
  2589. "300000" => "004",
  2590. "400000" => "006",
  2591. "500000" => "008",
  2592. "700000" => "010",
  2593. "1000000" => "012",
  2594. "1500000" => "014",
  2595. "2000000" => "016",
  2596. "2500000" => "018",
  2597. "5000000" => "020",
  2598. "6000000" => "022"
  2599. );
  2600. $res = new MySanitizeClass;
  2601. $parser = new CHtmlPurifier();
  2602. if(is_array(@$_REQUEST['ageGroupOfEldestMember'])){
  2603. @$_REQUEST['ageGroupOfEldestMember'] = '';
  2604. } else {
  2605. @$_REQUEST['ageGroupOfEldestMember'] = @$_REQUEST['ageGroupOfEldestMember'];
  2606. }
  2607. if(is_array(@$_REQUEST['numberOfAdult'])){
  2608. @$_REQUEST['numberOfAdult'] = '';
  2609. } else {
  2610. @$_REQUEST['numberOfAdult'] = @$_REQUEST['numberOfAdult'];
  2611. }
  2612. if(is_array(@$_REQUEST['coverTypeCd'])){
  2613. @$_REQUEST['coverTypeCd'] = '';
  2614. } else {
  2615. @$_REQUEST['coverTypeCd'] = @$_REQUEST['coverTypeCd'];
  2616. }
  2617. if(is_array(@$_REQUEST['numberOfChildren'])){
  2618. @$_REQUEST['numberOfChildren'] = '';
  2619. } else {
  2620. @$_REQUEST['numberOfChildren'] = @$_REQUEST['numberOfChildren'];
  2621. }
  2622. if(is_array(@$_REQUEST['productId'])){
  2623. @$_REQUEST['productId'] = '';
  2624. } else {
  2625. @$_REQUEST['productId'] = @$_REQUEST['productId'];
  2626. }
  2627. if(is_array(@$_REQUEST['productTerm'])){
  2628. @$_REQUEST['productTerm'] = '';
  2629. } else {
  2630. @$_REQUEST['productTerm'] = @$_REQUEST['productTerm'];
  2631. }
  2632. if(is_array(@$_REQUEST['sumInsured'])){
  2633. @$_REQUEST['sumInsured'] = '';
  2634. } else {
  2635. @$_REQUEST['sumInsured'] = @$_REQUEST['sumInsured'];
  2636. }
  2637. if(is_array(@$_REQUEST['tenure'])){
  2638. @$_REQUEST['tenure'] = '';
  2639. } else {
  2640. @$_REQUEST['tenure'] = @$_REQUEST['tenure'];
  2641. }
  2642. $query['ageGroupOfEldestMember']=$parser->purify(@$_REQUEST['ageGroupOfEldestMember']);
  2643. $query['coverTypeCd']=$parser->purify(@$_REQUEST['coverTypeCd']);
  2644. $query['productId']=$parser->purify(@$productId1);
  2645. $query['productTerm']=$parser->purify(@$_REQUEST['productTerm']);
  2646. $query['sumInsured']=$parser->purify(@$_REQUEST['sumInsured']);
  2647. if(@$_REQUEST['coverTypeCd']=="INDIVIDUAL"){
  2648. $sumInsured=$parser->purify(intval(@$_REQUEST['sumInsured']));
  2649. if(@$sumInsured>0){
  2650. $sumInsured1=@$INDIVIDUAL[@$sumInsured];
  2651. }
  2652. $query['numberOfAdult']=$parser->purify(@$_REQUEST['numberOfAdult']);
  2653. $query['numberOfChildren']=0;
  2654. }else{
  2655. $sumInsured=$parser->purify(intval(@$_REQUEST['sumInsured']));
  2656. if(@$sumInsured>0){
  2657. $sumInsured1=@$FAMILYFLOATER[@$sumInsured];
  2658. }
  2659. $query['numberOfAdult']=$parser->purify(@$_REQUEST['numberOfAdult']);
  2660. $query['numberOfChildren']=$parser->purify(@$_REQUEST['numberOfChildren']);
  2661. }
  2662. $query['sumInsured1']=@$sumInsured1;
  2663. /*$_SESSION['ageGroupOfEldestMember']=@$query['ageGroupOfEldestMember'];// assign value to session for product tab
  2664. $_SESSION['coverTypeCd'] =@$query['coverTypeCd'];// assign value to session for product tab
  2665. $_SESSION['numberOfAdult'] =@$query['numberOfAdult']+$query['numberOfChildren'];// assign value to session for product tab
  2666. $_SESSION['numberOfChildren'] =@$query['numberOfChildren'];// assign value to session for product tab
  2667. $_SESSION['sumInsured'] =@$sumInsured;// assign value to session for product tab*/
  2668. $premiumArray=$this->csvToArray('tempdata/care_premium.csv');
  2669. $totalMember=$query['numberOfAdult']+$query['numberOfChildren'];
  2670. $planKey=$query['coverTypeCd'].":".$query['ageGroupOfEldestMember'].":".@$totalMember.":".$query['numberOfChildren'].":".$query['sumInsured1'];
  2671. $exactPremiumArray=$this->search(@$premiumArray,'Plan',@$planKey);
  2672. $exactCarePremiumArray=explode(":",@$exactPremiumArray[0]['Premium']);
  2673. $tenureidx = @$_REQUEST['tenure']-1;
  2674. $carePremium = @$exactCarePremiumArray[@$tenureidx];
  2675. //print_r($exactCarePremiumArray);
  2676. $ncppremiumArray=$this->csvToArray('tempdata/ncb_premium.csv');
  2677. $ncbtotalMember=$query['numberOfAdult']+$query['numberOfChildren'];
  2678. $ncbplanKey=$query['coverTypeCd'].":".$query['ageGroupOfEldestMember'].":".@$ncbtotalMember.":".$query['numberOfChildren'].":".$query['sumInsured1'];
  2679. $ncbexactPremiumArray=$this->search(@$ncppremiumArray,'Plan',@$ncbplanKey);
  2680. $exactNCBPremiumArray=explode(":",@$ncbexactPremiumArray[0]['Premium']);
  2681. //$tenureidx = $_REQUEST['tenure']-1;
  2682. $ncbPremium = @$exactNCBPremiumArray[@$tenureidx];
  2683. $addCarePremium = str_replace(',','',@$carePremium);
  2684. $addNCBPremium = str_replace(',','',@$ncbPremium);
  2685. $finalNcbPremium = number_format($addNCBPremium+$addCarePremium);
  2686. //print_r($premiumArray);
  2687. echo trim(@$carePremium).':'.trim(@$finalNcbPremium);
  2688. // echo @$exactPremiumArray[0]['Premium'];
  2689. //$this->render('lead_search',array('searched'=>$searched));
  2690. }
  2691. function csvToArray($csvFileName){
  2692. $row = 1;
  2693. $dataArray=array();
  2694. $columnArray=array();
  2695. $k=0;
  2696. $i=0;
  2697. if (($handle = fopen($csvFileName, "r")) !== FALSE) {
  2698. while (($data = fgetcsv($handle, 10000, ",")) !== FALSE) {
  2699. $num = count($data);
  2700. if($k==0){
  2701. for ($c=0; $c < $num; $c++) {
  2702. $columnArray[$c]=@$data[$c];
  2703. }
  2704. }else{
  2705. for ($c=0; $c < $num; $c++) {
  2706. $columnName=$columnArray[$c];
  2707. $dataArray[$i][$columnName]=@$data[$c];
  2708. }
  2709. $i++;
  2710. }
  2711. $k++;
  2712. $row++;
  2713. }
  2714. fclose($handle);
  2715. }
  2716. return $dataArray;
  2717. }
  2718. function search($array, $key, $value){
  2719. $results = array();
  2720. if (is_array($array))
  2721. {
  2722. if (isset($array[$key]) && $array[$key] == $value)
  2723. $results[] = $array;
  2724. foreach ($array as $subarray){
  2725. $results = array_merge($results, $this->search($subarray, $key, $value));
  2726. }
  2727. }
  2728. return $results;
  2729. }
  2730. function quotesResults(){
  2731. }
  2732. public function actiongetPlanDetails(){
  2733. }
  2734. public function actionleadCreation(){
  2735. include_once("api/api.php");
  2736. $pageList = $this->xml2array(@file_get_contents(ADMINURL.'resource/product_subcategory.xml'),'1','');
  2737. $pageListArray = @$pageList['ProductSubCategory'];
  2738. $subcategoryList = $this->subcategory_page_array($pageListArray);
  2739. if(sanitize_data(@$_REQUEST['productId'])>0){
  2740. for($i=0; $i<count($subcategoryList); $i++){
  2741. if($subcategoryList[$i]["subCategoryId"]==sanitize_data($_REQUEST['productId']))
  2742. {
  2743. @$productId1="Care";
  2744. }
  2745. }
  2746. }else{
  2747. @$productId1="";
  2748. }
  2749. $query['coverTypeCd']=(@$_REQUEST['coverTypeCd']);
  2750. $query['productId']=@$productId1;
  2751. $query['sumInsured']=(@$_REQUEST['sumInsured']);
  2752. // if(@$_REQUEST['coverTypeCd']=="INDIVIDUAL"){
  2753. // switch(@$_REQUEST['sumInsured']){
  2754. // case '200000': $sumInsured1="001";
  2755. // break;
  2756. // case '300000': $sumInsured1="003";
  2757. // break;
  2758. // case '500000': $sumInsured1="005";
  2759. // break;
  2760. // case '1000000': $sumInsured1="007";
  2761. // break;
  2762. // default: $sumInsured1="007";
  2763. // break;
  2764. // }
  2765. // }else{
  2766. // switch(@$_REQUEST['sumInsured']){
  2767. // case '200000': $sumInsured1="002";
  2768. // break;
  2769. // case '300000': $sumInsured1="004";
  2770. // break;
  2771. // case '500000': $sumInsured1="006";
  2772. // break;
  2773. // case '1000000': $sumInsured1="008";
  2774. // break;
  2775. // default: $sumInsured1="008";
  2776. // break;
  2777. // }
  2778. // }
  2779. $tenure=(@$_REQUEST['tenure']);
  2780. $leadstage=(@$_POST['leadstage']);
  2781. $subject=(@$_POST['subject']);
  2782. $query['sumInsured1']=(@$_REQUEST['sumInsured']);
  2783. $query['firstname']=(@$_REQUEST["firstname"]);
  2784. $query['lastname']="";
  2785. $query['emailaddress1']=(@$_REQUEST["emailaddress1"]);
  2786. $query['telephone1']=(@$_REQUEST["telephone1"]);
  2787. $query['mobilephone']=(@$_REQUEST["mobilephone"]);
  2788. $query['premium']=(@$_REQUEST["premium".@$tenure]);
  2789. if(@$_SESSION['agentId']!=''){
  2790. $query['agentid']=@$_SESSION['agentId'];
  2791. }else{
  2792. $query['agentid']=AGENTID;
  2793. }
  2794. $query['noofyears']=@$tenure;
  2795. $query['quoteid']=time();
  2796. if(@$leadstage!=''){
  2797. $query['leadstage']=@$leadstage;
  2798. }else{
  2799. $query['leadstage']="SendQuotation";
  2800. }
  2801. if(@$subject!=''){
  2802. $query['subject']=@$subject." - ".(@$_REQUEST["mobilephone"]);
  2803. }else{
  2804. $query['subject']="Web-".(@$_REQUEST["mobilephone"]);
  2805. }
  2806. $dataArray= $this->LeadCreation($query);
  2807. $_SESSION["quotationReferenceNum"]=$query['quoteid'];
  2808. $_SESSION['mobileSend']="2";
  2809. $_SESSION['mobilephone']=(@$_REQUEST["mobilephone"]);
  2810. }
  2811. public function actionportalProposal(){
  2812. define("_SITEURL", "http://" . @$_SERVER['SERVER_NAME']. '/religare') ;
  2813. define("ADMINURL", "../", true);
  2814. global $INDIVIDUAL,$FAMILYFLOATER,$GroupCareArray;
  2815. $GroupCareArray = array("200000" => "2 Lac + 2 Lac", "300000" => "3 Lac + 3 Lac", "400000" => "4 Lac + 4 Lac", "500000" => "5 Lac + 5 Lac", "700000" => "7 Lac + 7 Lac", "1000000" => "10 Lac + 10 Lac", "1500000" => "15 Lac + 10 Lac", "2000000" => "20 Lac + 10 Lac", "2500000" => "25 Lac + 10 Lac", "5000000" => "50 Lac + 10 Lac", "6000000" => "60 Lac + 10 Lac");
  2816. $INDIVIDUAL = array(
  2817. "200000" => "001",
  2818. "300000" => "003",
  2819. "400000" => "005",
  2820. "500000" => "007",
  2821. "700000" => "009",
  2822. "1000000" => "011",
  2823. "1500000" => "013",
  2824. "2000000" => "015",
  2825. "2500000" => "017",
  2826. "5000000" => "019",
  2827. "6000000" => "021"
  2828. );
  2829. $FAMILYFLOATER = array(
  2830. "200000" => "002",
  2831. "300000" => "004",
  2832. "400000" => "006",
  2833. "500000" => "008",
  2834. "700000" => "010",
  2835. "1000000" => "012",
  2836. "1500000" => "014",
  2837. "2000000" => "016",
  2838. "2500000" => "018",
  2839. "5000000" => "020",
  2840. "6000000" => "022"
  2841. );
  2842. $WEBSUMINSURED = array(
  2843. "200000" => "1",
  2844. "300000" => "2",
  2845. "400000" => "3",
  2846. "500000" => "4",
  2847. "700000" => "5",
  2848. "1000000" => "6",
  2849. "1500000" => "7",
  2850. "2000000" => "8",
  2851. "2500000" => "9",
  2852. "5000000" => "10",
  2853. "6000000" => "11"
  2854. );
  2855. $WEBSUMINSURED1 = array(
  2856. "1" => "200000",
  2857. "2" => "300000",
  2858. "3" => "400000",
  2859. "4" => "500000",
  2860. "5" => "700000",
  2861. "6" => "1000000",
  2862. "7" => "1500000",
  2863. "8" => "2000000",
  2864. "9" => "2500000",
  2865. "10" => "5000000",
  2866. "11" => "6000000"
  2867. );
  2868. $proposalURL="https://rhicluat.religare.com/portalui/PortalExtProposal.run";
  2869. $pageList = $this->xml2array(@file_get_contents('resource/product_subcategory.xml'),'1','');
  2870. $pageListArray = @$pageList['ProductSubCategory'];
  2871. $subcategoryList = $this->subcategory_page_array($pageListArray);
  2872. $productId=(@$_POST['productId']);
  2873. $sumInsured=(@$_POST['sumInsured']);
  2874. $tenure=(@$_POST['premium']);
  2875. $totalAdults=(@$_POST['numberOfAdult']);
  2876. $numberOfChildren=(@$_POST['numberOfChildren']);
  2877. $numberOfAdult=$totalAdults-$numberOfChildren;
  2878. $mobileNumber=(@$_POST['mobile']);
  2879. $_SESSION['mobilephone']=$mobileNumber;
  2880. if($productId>0){
  2881. for($i=0; $i<count($subcategoryList); $i++){
  2882. if($subcategoryList[$i]["subCategoryId"]==$productId)
  2883. {
  2884. @$productId1=$subcategoryList[$i]["productCode"];
  2885. }
  2886. }
  2887. }else{
  2888. @$productId1="";
  2889. }
  2890. if(($tenure==1) || ($tenure==2) || ($tenure==3)){}else{header("Location: "._SITEURL);exit;}
  2891. if($productId1==""){header("Location: "._SITEURL);exit;}else{}
  2892. if(($numberOfChildren==0) || ($numberOfChildren==1) || ($numberOfChildren==2) || ($numberOfChildren==3) || ($numberOfChildren==4)){}else{ header("Location: "._SITEURL);exit;}
  2893. if($totalAdults>1){
  2894. $ageGroupOfEldestMember=(@$_POST['ageGroupOfEldestMember']);
  2895. switch($ageGroupOfEldestMember){
  2896. case '18 - 24': $ageGroupOfEldestMember="18 - 24";
  2897. break;
  2898. case '25 - 35': $ageGroupOfEldestMember="25 - 35";
  2899. break;
  2900. case '36 - 40': $ageGroupOfEldestMember="36 - 40";
  2901. break;
  2902. case '41 - 45': $ageGroupOfEldestMember="41 - 45";
  2903. break;
  2904. case '46 - 50': $ageGroupOfEldestMember="46 - 50";
  2905. break;
  2906. case '51 - 55': $ageGroupOfEldestMember="51 - 55";
  2907. break;
  2908. case '56 - 60': $ageGroupOfEldestMember="56 - 60";
  2909. break;
  2910. case '61 - 65': $ageGroupOfEldestMember="61 - 65";
  2911. break;
  2912. case '66 - 70': $ageGroupOfEldestMember="66 - 70";
  2913. break;
  2914. case '71 - 75': $ageGroupOfEldestMember="71 - 75";
  2915. break;
  2916. case '76 - 99': $ageGroupOfEldestMember="76 - 99";
  2917. break;
  2918. default: $ageGroupOfEldestMember="";
  2919. break;
  2920. }
  2921. if($ageGroupOfEldestMember==""){header("Location: "._SITEURL);exit;}else{}
  2922. $coverType="FAMILYFLOATER";
  2923. if(@$sumInsured>0){
  2924. $sumInsured1=$FAMILYFLOATER[@$sumInsured];
  2925. }
  2926. if($sumInsured1==""){header("Location: "._SITEURL);exit;}else{}
  2927. //$url1="&numberOfAdult=".@$numberOfAdult."&numberOfChildren=".@$numberOfChildren;
  2928. // $url="Location: ".@$proposalURL."?productFamily=HEALTH&pCode=".@$productId1."&coverType=FAMILYFLOATER&ageGroupOfEldestMember=".@$ageGroupOfEldestMember."&sumInsured=".@$sumInsured1."&tenure=".@$tenure.$url1."&mobileNum=".@$_POST['mobile'];
  2929. }else if($totalAdults=="1"){
  2930. $ageGroupOfEldestMember=@$_POST['ageGroupOfEldestMember'];
  2931. switch($ageGroupOfEldestMember){
  2932. case '5 - 24': $ageGroupOfEldestMember="5 - 24";
  2933. break;
  2934. case '25 - 35': $ageGroupOfEldestMember="25 - 35";
  2935. break;
  2936. case '36 - 40': $ageGroupOfEldestMember="36 - 40";
  2937. break;
  2938. case '41 - 45': $ageGroupOfEldestMember="41 - 45";
  2939. break;
  2940. case '46 - 50': $ageGroupOfEldestMember="46 - 50";
  2941. break;
  2942. case '51 - 55': $ageGroupOfEldestMember="51 - 55";
  2943. break;
  2944. case '56 - 60': $ageGroupOfEldestMember="56 - 60";
  2945. break;
  2946. case '61 - 65': $ageGroupOfEldestMember="61 - 65";
  2947. break;
  2948. case '66 - 70': $ageGroupOfEldestMember="66 - 70";
  2949. break;
  2950. case '71 - 75': $ageGroupOfEldestMember="71 - 75";
  2951. break;
  2952. case '76 - 99': $ageGroupOfEldestMember="76 - 99";
  2953. break;
  2954. default: $ageGroupOfEldestMember="";
  2955. break;
  2956. }
  2957. $coverType="INDIVIDUAL";
  2958. if($ageGroupOfEldestMember==""){header("Location: "._SITEURL);exit;}else{}
  2959. if(@$sumInsured>0){
  2960. $sumInsured1=$INDIVIDUAL[@$sumInsured];
  2961. }
  2962. if($sumInsured1==""){header("Location: "._SITEURL);exit;}else{}
  2963. $numberOfAdult=0;
  2964. $numberOfChildren=0;
  2965. // $url1="&numberOfAdult=0&numberOfChildren=0";
  2966. //$url="Location: ".@$proposalURL."?productFamily=HEALTH&pCode=".@$productId1."&coverType=INDIVIDUAL&ageGroupOfEldestMember=".@$ageGroupOfEldestMember."&sumInsured=".@$sumInsured1."&tenure=".@$tenure.$url1."&mobileNum=".@$_SESSION['mobilephone'];
  2967. }else{
  2968. header("Location: "._SITEURL);exit;
  2969. }
  2970. ?>
  2971. <form name="PortalProposal" id="PortalProposal" method="post" action="<?=@$proposalURL;?>">
  2972. <input type="hidden" name="productFamily" value="HEALTH" />
  2973. <input type="hidden" name="pCode" value="<?=@$productId1;?>" />
  2974. <input type="hidden" name="coverType" value="<?=@$coverType;?>" />
  2975. <input type="hidden" name="ageGroupOfEldestMember" value="<?=@$ageGroupOfEldestMember;?>" />
  2976. <input type="hidden" name="sumInsured" value="<?=@$sumInsured1;?>" />
  2977. <input type="hidden" name="tenure" value="<?=@$tenure;?>" />
  2978. <input type="hidden" name="numberOfAdult" value="<?=@$numberOfAdult;?>" />
  2979. <input type="hidden" name="numberOfChildren" value="<?=@$numberOfChildren;?>" />
  2980. <input type="hidden" name="mobileNum" value="<?=@$mobileNumber;?>" />
  2981. <input type="hidden" name="quotationReferenceNum" value="<?=@$_SESSION['quotationReferenceNum'];?>" />
  2982. <input type="hidden" name="agentId" value="<?=@$_SESSION['agentId'];?>" />
  2983. </form>
  2984. <script>
  2985. document.PortalProposal.submit();
  2986. </script>
  2987. <?php
  2988. }
  2989. function xml2array($contents, $get_attributes=1, $priority = 'tag'){
  2990. if(!$contents) return array();
  2991. if(!function_exists('xml_parser_create')) {
  2992. //print "'xml_parser_create()' function not found!";
  2993. return array();
  2994. }
  2995. //Get the XML parser of PHP - PHP must have this module for the parser to work
  2996. $parser = xml_parser_create('');
  2997. xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
  2998. xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  2999. xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  3000. xml_parse_into_struct($parser, trim($contents), $xml_values);
  3001. xml_parser_free($parser);
  3002. if(!$xml_values) return;//Hmm...
  3003. //Initializations
  3004. $xml_array = array();
  3005. $parents = array();
  3006. $opened_tags = array();
  3007. $arr = array();
  3008. $current = &$xml_array; //Refference
  3009. //Go through the tags.
  3010. $repeated_tag_index = array();//Multiple tags with same name will be turned into an array
  3011. foreach($xml_values as $data) {
  3012. unset($attributes,$value);//Remove existing values, or there will be trouble
  3013. //This command will extract these variables into the foreach scope
  3014. // tag(string), type(string), level(int), attributes(array).
  3015. extract($data);//We could use the array by itself, but this cooler.
  3016. $result = array();
  3017. $attributes_data = array();
  3018. if(isset($value)) {
  3019. if($priority == 'tag') $result = $value;
  3020. else $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode
  3021. }
  3022. //Set the attributes too.
  3023. if(isset($attributes) and $get_attributes) {
  3024. foreach($attributes as $attr => $val) {
  3025. if($priority == 'tag') $attributes_data[$attr] = $val;
  3026. else $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
  3027. }
  3028. }
  3029. //See tag status and do the needed.
  3030. if($type == "open") {//The starting of the tag '<tag>'
  3031. $parent[$level-1] = &$current;
  3032. if(!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag
  3033. $current[$tag] = $result;
  3034. if($attributes_data) $current[$tag. '_attr'] = $attributes_data;
  3035. $repeated_tag_index[$tag.'_'.$level] = 1;
  3036. $current = &$current[$tag];
  3037. } else { //There was another element with the same tag name
  3038. if(isset($current[$tag][0])) {//If there is a 0th element it is already an array
  3039. $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
  3040. $repeated_tag_index[$tag.'_'.$level]++;
  3041. } else {//This section will make the value an array if multiple tags with the same name appear together
  3042. $current[$tag] = array($current[$tag],$result);//This will combine the existing item and the new item together to make an array
  3043. $repeated_tag_index[$tag.'_'.$level] = 2;
  3044. if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well
  3045. $current[$tag]['0_attr'] = $current[$tag.'_attr'];
  3046. unset($current[$tag.'_attr']);
  3047. }
  3048. }
  3049. $last_item_index = $repeated_tag_index[$tag.'_'.$level]-1;
  3050. $current = &$current[$tag][$last_item_index];
  3051. }
  3052. } elseif($type == "complete") { //Tags that ends in 1 line '<tag />'
  3053. //See if the key is already taken.
  3054. if(!isset($current[$tag])) { //New Key
  3055. $current[$tag] = $result;
  3056. $repeated_tag_index[$tag.'_'.$level] = 1;
  3057. if($priority == 'tag' and $attributes_data) $current[$tag. '_attr'] = $attributes_data;
  3058. } else { //If taken, put all things inside a list(array)
  3059. if(isset($current[$tag][0]) and is_array($current[$tag])) {//If it is already an array...
  3060. // ...push the new element into that array.
  3061. $current[$tag][$repeated_tag_index[$tag.'_'.$level]] = $result;
  3062. if($priority == 'tag' and $get_attributes and $attributes_data) {
  3063. $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
  3064. }
  3065. $repeated_tag_index[$tag.'_'.$level]++;
  3066. } else { //If it is not an array...
  3067. $current[$tag] = array($current[$tag],$result); //...Make it an array using using the existing value and the new value
  3068. $repeated_tag_index[$tag.'_'.$level] = 1;
  3069. if($priority == 'tag' and $get_attributes) {
  3070. if(isset($current[$tag.'_attr'])) { //The attribute of the last(0th) tag must be moved as well
  3071. $current[$tag]['0_attr'] = $current[$tag.'_attr'];
  3072. unset($current[$tag.'_attr']);
  3073. }
  3074. if($attributes_data) {
  3075. $current[$tag][$repeated_tag_index[$tag.'_'.$level] . '_attr'] = $attributes_data;
  3076. }
  3077. }
  3078. $repeated_tag_index[$tag.'_'.$level]++; //0 and 1 index is already taken
  3079. }
  3080. }
  3081. } elseif($type == 'close') { //End of tag '</tag>'
  3082. $current = &$parent[$level-1];
  3083. }
  3084. }
  3085. return($xml_array);
  3086. }
  3087. function subcategory_page_array($pageListArray1){
  3088. $m =0;
  3089. $dataArr=array();
  3090. if(is_array(@$pageListArray1['subcategory'][0]) ) {
  3091. $pageListArray = $pageListArray1['subcategory'];
  3092. for($i=0;$i<sizeof($pageListArray);$i++) {
  3093. if(trim($pageListArray[$i]['isDeleted']['value'])=='no'){
  3094. $dataArr[$m]['subCategoryId'] = trim($pageListArray[$i]['subCategoryId']['value']);
  3095. $dataArr[$m]['categoryId'] =trim(@$pageListArray[$i]['categoryId']['value']);
  3096. $dataArr[$m]['subCategoryName'] = @$pageListArray[$i]['subCategoryName']['value'];
  3097. $dataArr[$m]['productCode'] = @$pageListArray[$i]['productCode']['value'];
  3098. $dataArr[$m]['description'] = @$pageListArray[$i]['description']['value'];
  3099. $dataArr[$m]['briefDescription'] = @$pageListArray[$i]['briefDescription']['value'];
  3100. $dataArr[$m]['metaTitle'] = @$pageListArray[$i]['metaTitle']['value'];
  3101. $dataArr[$m]['metaDescription'] = @$pageListArray[$i]['metaDescription']['value'];
  3102. $dataArr[$m]['metaKeywords'] = @$pageListArray[$i]['metaKeywords']['value'];
  3103. $dataArr[$m]['compare'] = @$pageListArray[$i]['compare']['value'];
  3104. $dataArr[$m]['exclusions'] =@$pageListArray[$i]['exclusions']['value'];
  3105. $dataArr[$m]['policyTerms'] =@$pageListArray[$i]['policyTerms']['value'];
  3106. $dataArr[$m]['agentpolicyTerms'] =@$pageListArray[$i]['agentpolicyTerms']['value'];
  3107. $dataArr[$m]['claim'] = @$pageListArray[$i]['claim']['value'];
  3108. $dataArr[$m]['logo'] = @$pageListArray[$i]['logo']['value'];
  3109. $dataArr[$m]['thumbnail'] = @$pageListArray[$i]['thumbnail']['value'];
  3110. $dataArr[$m]['isDeleted'] = trim($pageListArray[$i]['isDeleted']['value']);
  3111. $m++;
  3112. }
  3113. }
  3114. }else {
  3115. $pageListArray = @$pageListArray1['subcategory'];
  3116. if(trim($pageListArray['isDeleted']['value']) =='no') {
  3117. $dataArr[$m]['subCategoryId'] = trim($pageListArray['subCategoryId']['value']);
  3118. $dataArr[$m]['categoryId'] = trim($pageListArray['categoryId']['value']);
  3119. $dataArr[$m]['subCategoryName'] = $pageListArray['subCategoryName']['value'];
  3120. $dataArr[$m]['productCode'] = @$pageListArray['productCode']['value'];
  3121. $dataArr[$m]['description'] = $pageListArray['description']['value'];
  3122. $dataArr[$m]['briefDescription']= $pageListArray['briefDescription']['value'];
  3123. $dataArr[$m]['metaTitle'] = $pageListArray['metaTitle']['value'];
  3124. $dataArr[$m]['metaDescription'] = $pageListArray['metaDescription']['value'];
  3125. $dataArr[$m]['metaKeywords'] = $pageListArray['metaKeywords']['value'];
  3126. $dataArr[$m]['compare'] = $pageListArray['compare']['value'];
  3127. $dataArr[$m]['exclusions'] = $pageListArray['exclusions']['value'];
  3128. $dataArr[$m]['claim'] = $pageListArray['claim']['value'];
  3129. $dataArr[$m]['policyTerms'] =@$pageListArray['policyTerms']['value'];
  3130. $dataArr[$m]['agentpolicyTerms'] =@$pageListArray['agentpolicyTerms']['value'];
  3131. $dataArr[$m]['logo'] = @$pageListArray['logo']['value'];
  3132. $dataArr[$m]['thumbnail'] = @$pageListArray['thumbnail']['value'];
  3133. $dataArr[$m]['isDeleted'] = trim($pageListArray[$i]['isDeleted']['value']);
  3134. $m++;
  3135. }
  3136. }
  3137. //sort by
  3138. if (count ($dataArr) > 0) {
  3139. foreach ($dataArr as $key => $row) {
  3140. @$order_in_category[$key] = $row[0];//[0] is @$order_in_category
  3141. }
  3142. @array_multisort(@$order_in_category, SORT_ASC, $dataArr);
  3143. }
  3144. return $dataArr;
  3145. }
  3146. public function actiongetWebserviceLeadXMLResponse(){
  3147. $data='';
  3148. $leadURL=$_SERVER['DOCUMENT_ROOT']."/religarewebservices/data";
  3149. $r=0;
  3150. foreach(glob($leadURL . '/*request.xml') as $files){
  3151. $checkLeadExistorNot=Lead::model()->findByAttributes(array('fileName'=>$files));
  3152. if(count($checkLeadExistorNot)==0){
  3153. $data=file_get_contents($files);
  3154. $result=$this->xml2array($data);
  3155. $createdLeadDetails=$result['SOAP:Envelope']['SOAP:Body']['Createlead']['Lead'];
  3156. $OrganizationName=$result['SOAP:Envelope']['SOAP:Body']['Createlead']['OrganizationName'];
  3157. $type='Lead';
  3158. $leadsourceCode=$createdLeadDetails['leadsourcecode'];
  3159. $subject=$createdLeadDetails['subject'];
  3160. $firstname=$createdLeadDetails['firstname'];
  3161. $lastname=$createdLeadDetails['lastname'];
  3162. $emailaddress1=$createdLeadDetails['emailaddress1'];
  3163. $telephone1=$createdLeadDetails['telephone1'];
  3164. $mobilephone=$createdLeadDetails['mobilephone'];
  3165. $product=$createdLeadDetails['rhi_product'];
  3166. $suminsured=$createdLeadDetails['rhi_suminsured'];
  3167. $suminsured=(count($suminsured) > 0)?$suminsured:0;
  3168. $premium=$createdLeadDetails['rhi_premium'];
  3169. $premium=(count($premium) > 0)?$premium:0;
  3170. $quoteid=$createdLeadDetails['rhi_quoteid'];
  3171. $proposalid=$createdLeadDetails['rhi_proposalid'];
  3172. $leadstage=$createdLeadDetails['rhi_leadstage'];
  3173. $agentid=$createdLeadDetails['rhi_agentid'];
  3174. $noofyears=$createdLeadDetails['rhi_noofyears'];
  3175. $ProductMaster=ProductMaster::model()->findByAttributes(array('productName'=>$product));
  3176. $productId=$ProductMaster['productId'];
  3177. if(count($result) > 0){
  3178. //echo $files;
  3179. $model = new Lead;
  3180. $model->setAttributes(array(
  3181. 'name' => 'web services',
  3182. 'email' => '',
  3183. 'mobile' => $mobilephone,
  3184. 'productId' => $productId,
  3185. 'members' => 0,
  3186. 'si' => $suminsured,
  3187. 'premium' => $premium,
  3188. 'leadStageId' => '',
  3189. 'fileName' => addslashes($files),
  3190. 'status' => 'Active',
  3191. 'createdOn' => time(),
  3192. 'updatedOn' => time(),
  3193. 'updatedBy' => time(),
  3194. 'createdBy' => time(),
  3195. ));
  3196. //print_r($model);
  3197. $model->isNewRecord = true;
  3198. @$model->save(false);
  3199. } $r++;
  3200. }
  3201. }
  3202. $this->redirect(array('leads/lead_list'));
  3203. }
  3204. public function actionfresh_leads()
  3205. {
  3206. //$modelLead = Lead::model()->findAll("leadStatusId = '34' AND currentAllocatedId<1 ");
  3207. $this->render('fresh_lead_list');
  3208. }
  3209. public function actionviewAllTeams() {
  3210. if (!Yii::app()->request->isAjaxRequest){
  3211. }
  3212. else {
  3213. $this->renderPartial('/leads/partialAllTeamDetails');
  3214. Yii::app()->end();
  3215. }
  3216. }
  3217. public function actionViewLeadActivity() {
  3218. $followupId=@$_REQUEST['id'];
  3219. $model=new LeadFollowup;
  3220. $model=LeadFollowup::model()->findByPk($followupId);
  3221. if (!Yii::app()->request->isAjaxRequest){
  3222. // $this->render('yourView');
  3223. }
  3224. else {
  3225. $this->renderPartial('/leads/ViewLeadActivity',array('model'=>$model));
  3226. Yii::app()->end();
  3227. }
  3228. }
  3229. public function actionViewCalenderActs() {
  3230. //$cs = Yii::app()->getClientScript(); $cs->registerCoreScript('jquery');
  3231. $this->layout=false;
  3232. $startDate=@$_REQUEST['id'];
  3233. $model = LeadFollowup::model()->findAll(array("condition"=>"startDate = '".@$startDate."' AND userId = '".@$_SESSION['id']."' AND STATUS = 'Pending' AND (actionType = 'Meeting' OR actionType = 'Follow Up') ORDER BY hour DESC"));
  3234. if (!Yii::app()->request->isAjaxRequest){
  3235. $this->renderPartial('/leads/ViewCalenderActs',array('model'=>$model,'startDate'=>@$startDate));
  3236. }
  3237. else {
  3238. $this->renderPartial('/leads/ViewCalenderActs',array('model'=>$model,'startDate'=>@$startDate));
  3239. Yii::app()->end();
  3240. }
  3241. }
  3242. public function actionEditCalenderActivity() {
  3243. $this->layout=false;
  3244. $leadId=@$_REQUEST['leadId'];
  3245. $actionId=@$_REQUEST['actionId'];
  3246. $this->renderPartial('EditCalenderActivity',array('leadId'=>$leadId,'actionId'=>$actionId) ,false, true);
  3247. Yii::app()->end();
  3248. }
  3249. public function actiongetActionRes(){
  3250. $statusids = @$_POST['statusids'];
  3251. $model = new LeadStatus;
  3252. $model=LeadStatus::model()->findByPk($statusids);
  3253. echo $result = @$model['actionCompulsary'];
  3254. }
  3255. public function actioncip_lead_list()
  3256. {
  3257. //$model = new LeadStatus;
  3258. $this->render('contact_in_progress_lead_list');
  3259. }
  3260. public function actioncld_lead_list()
  3261. {
  3262. //$model = new Lead;
  3263. $this->render('cld_lead_list');
  3264. }
  3265. public function actionsearchCIP(){
  3266. if(Yii::app()->request->isAjaxRequest==1){
  3267. $models=new Lead();
  3268. $searchIDs =@$_REQUEST['searchIDs'];
  3269. if(isset($searchIDs) && !empty($searchIDs)){
  3270. $this->renderPartial('partialcip',array('searchTxt'=>$searchIDs,'type'=>'cip'));
  3271. }
  3272. } else {
  3273. $redirectUrl = Yii::app()->controller->id."/".$this->action->id;
  3274. $this->redirect("index.php?r=leads/cip_lead_list&pageSize=".@$_REQUEST['pageSize']);
  3275. }
  3276. }
  3277. public function actiondup_forthe_day_lead_list()
  3278. {
  3279. //$modelLead = new Lead;
  3280. $this->render('duplicate_forthe_daylead_list');
  3281. }
  3282. public function actionSearchArchiveLeads(){
  3283. $model = new Lead;
  3284. $teamId = @$_POST['Team']['teamId'];
  3285. $Leadname = @$_POST['Lead']['name'];
  3286. $Leadstatus = @$_POST['Lead']['status'];
  3287. $leadStage = @$_POST['Lead']['leadStage'];
  3288. $leadws_agentid = @$_POST['Lead']['ws_agentid'];
  3289. $leademail = @$_POST['Lead']['email'];
  3290. $leadmobile = @$_POST['Lead']['mobile'];
  3291. $this->render('archive_leads',array('model'=>$model,'teamId'=>$teamId,'Leadname'=>$Leadname,'Leadstatus'=>$Leadstatus,'leadStage'=>$leadStage,'Leadmobile'=>$leadmobile,'Leademail'=>$leademail,'Leadws_agentid'=>$leadws_agentid));
  3292. }
  3293. public function actionplc_lead_list()
  3294. {
  3295. //$model = new Lead;
  3296. $this->render('plc_lead_list');
  3297. }
  3298. public function getAgentIds($ws_agentid,$mobile){
  3299. $agentIds=Yii::app()->db->createCommand("select group_concat(distinct ws_agentid) as ws_agentid,count(distinct ws_agentid) as total from lead where mobile='".@$mobile."' and ws_agentid!='' order by leadId desc ")->queryAll();
  3300. if( $agentIds[0]['total'] > 1){
  3301. echo "<label class='linkUnderline' title='".@$agentIds[0]['ws_agentid']."'><a href='#'>".$ws_agentid."</a></label>";
  3302. } else if($agentIds[0]['total'] == 1) {
  3303. echo "<label title='".@$agentIds[0]['ws_agentid']."'><a href='#'>".$ws_agentid."</a></label>";
  3304. } else {
  3305. echo "";
  3306. }
  3307. //echo explode(',',$agentId);
  3308. }
  3309. public function getLeadStagesIds($leadStageId,$mobile){
  3310. $agentIds=Yii::app()->db->createCommand("select distinct leadStageId from lead where mobile='".@$mobile."' and leadStageId!='' order by leadId desc ")->queryAll();
  3311. $displayedSyage=Yii::app()->db->createCommand("select leadStage from leadStageMaster where leadStageId='".@$leadStageId."' ")->queryAll();
  3312. if(count($agentIds) > 0) {
  3313. for($i=0;$i<count($agentIds);$i++){
  3314. $leadstages=Yii::app()->db->createCommand("select leadStage from leadStageMaster where leadStageId='".@$agentIds[$i]['leadStageId']."' ")->queryAll();
  3315. $agentId[] = @$agentIds[$i]['leadStageId'];
  3316. $leadstages_new[] = @$leadstages[0]['leadStage'];
  3317. }
  3318. } else {
  3319. echo "";
  3320. }
  3321. if( count(@$leadstages_new) > 1){
  3322. echo "<label class='linkUnderline' title='".implode(',',$leadstages_new)."'><a href='#'>".@$displayedSyage[0]['leadStage']."</a></label>";
  3323. } else if( count(@$leadstages_new) == 1) {
  3324. echo "<label title='".implode(',',@$leadstages_new)."'><a href='#'>".@$displayedSyage[0]['leadStage']."</a></label>";
  3325. } else {
  3326. echo "";
  3327. }
  3328. //echo explode(',',$agentId);
  3329. }
  3330. public function actioninactive_users_leads()
  3331. {
  3332. $this->render('inactive_users_leads');
  3333. }
  3334. public function actionInactiveAllocateLeads()
  3335. {
  3336. $Id = $_REQUEST['userids'];
  3337. $teamId = @$_REQUEST['Team']['teamId'];
  3338. $userId = $_REQUEST['Team']['teamMemberId'];
  3339. $updatedBy = @$_SESSION['id'];
  3340. foreach($Id as $key=>$value){
  3341. $model = new AllocatedLeads();
  3342. $model->scenario = 'AllocatedLeads';
  3343. $model->setAttributes(array(
  3344. 'currentAllocatedDate' => time(), //additional data you want to insert
  3345. 'createdOn' => time(), //additional data you want to insert
  3346. 'updatedOn' => time(), //additional
  3347. 'updatedBy' => @$updatedBy, //additional
  3348. 'createdBy' => @$updatedBy, //additional
  3349. 'leadStatusId' => '35', //additional //additional
  3350. ));
  3351. $leadId = @$value;
  3352. $model->leadId = @$value;
  3353. $model->userId = @$userId;
  3354. $model->teamId = @$teamId;
  3355. //echo @$teamId.' - '.@$userId.' - '.@$leadId;
  3356. $model->allocatedId = null;
  3357. $model->isNewRecord = true;
  3358. $model->save();
  3359. $model=new Lead();
  3360. $model->scenario = 'Lead';
  3361. $updatedOn = time();
  3362. Lead::model()->updateByPk(@$value, array('currentAllocatedId'=>@$userId,'leadStatusId'=>'35','updatedBy'=>@$updatedBy,'updatedOn'=>@$updatedOn,'currentAllocatedDate'=>@$updatedOn));
  3363. }
  3364. $red = @$_REQUEST['red'];
  3365. if($this->action->id=='AllocateLeads' && $red == 1) {
  3366. $this->redirect(array('leads/inactive_users_leads'));
  3367. } else {
  3368. $this->redirect(array('leads/inactive_users_leads'));
  3369. }
  3370. //$this->redirect(array('leads/lead_list'));
  3371. }
  3372. public function getLeadDescription($leadId){
  3373. $records=Yii::app()->db->createCommand("select leadDescription from lead where leadId='".@$leadId."' ")->queryAll();
  3374. if(count($records) > 0) {
  3375. for($i=0;$i<count($records);$i++){
  3376. $record[] = @$records[$i]['leadDescription'];
  3377. }
  3378. } else {
  3379. echo "";
  3380. }
  3381. if( count(@$record) > 1){
  3382. echo "<label title='".implode(',',$record)."'><a href='#'>".substr(implode(',',$record),0,5)."...</a></label>";
  3383. } else if( count(@$record) == 1) {
  3384. echo "<label title='".implode(',',@$record)."'><a href='#'>".implode(',',$record)."</a></label>";
  3385. } else {
  3386. echo "";
  3387. }
  3388. //echo explode(',',$agentId);
  3389. }
  3390. public function getLeadActivityDescription($leadId){
  3391. $records=Yii::app()->db->createCommand("select description from leadFollowup where leadId='".@$leadId."' ")->queryAll();
  3392. if(count($records) > 0) {
  3393. for($i=0;$i<count($records);$i++){
  3394. $record[] = @$records[$i]['description'];
  3395. }
  3396. } else {
  3397. echo "";
  3398. }
  3399. if( count(@$record) > 1){
  3400. echo "<label title='".implode(',',$record)."'><a href='#'>".substr(implode(',',$record),0,5)."...</a></label>";
  3401. } else if( count(@$record) == 1) {
  3402. echo "<label title='".implode(',',@$record)."'><a href='#'>".substr(implode(',',$record),0,5)."...</a></label>";
  3403. } else {
  3404. echo "";
  3405. }
  3406. //echo explode(',',$agentId);
  3407. }
  3408. public function actionloadleadtabs(){
  3409. $this->layout = false;
  3410. $this->renderPartial('leadTabs');
  3411. }
  3412. public function actiondeleted_database_tab()
  3413. {
  3414. $model=new Lead();
  3415. $model->set_period1=@$_POST['Lead']['period1']?@$_POST['Lead']['period1']:@$_REQUEST['period1'];
  3416. $model->set_period2=@$_POST['Lead']['period2']?@$_POST['Lead']['period2']:@$_REQUEST['period2'];
  3417. $this->render('deleted_database_tab',array('model'=>$model));
  3418. }
  3419. public function actiondelete_lead()
  3420. {
  3421. $deleteId=@$_REQUEST['leadId'];
  3422. if(Yii::app()->request->isAjaxRequest){
  3423. if(!empty($deleteId))
  3424. {
  3425. $model=Lead::model()->findByPk($deleteId);
  3426. }
  3427. else
  3428. {
  3429. $model = new Lead();
  3430. }
  3431. if($model->delete($deleteId)){
  3432. echo "Record deleted successfully";
  3433. } else {
  3434. echo "some error occured please try after some time";
  3435. }
  3436. } else {
  3437. $this->redirect(array('leads/deleted_database_tab'));
  3438. }
  3439. }
  3440. public function actionDeleteAllJunkLeads()
  3441. {
  3442. $model = new lead;
  3443. //print_r($_REQUEST);
  3444. $Id=$_REQUEST['leadids'];
  3445. foreach($Id as $key=>$value){
  3446. $model->deleteByPk($value);
  3447. }
  3448. $this->redirect(Yii::app()->request->urlReferrer);
  3449. }
  3450. public function actionDeleteAllJunkLeadsOneTime()
  3451. {
  3452. $model = new lead;
  3453. echo $startDate = @$_REQUEST['period1'];
  3454. $endDate = @$_REQUEST['period2'];
  3455. $alldeletedIds = @$_POST['alldeletedIds'];
  3456. $Id=unserialize(urldecode($_POST['alldeletedIds']));
  3457. foreach($Id as $key=>$value){
  3458. //echo $value;
  3459. $model->deleteByPk($value);
  3460. }
  3461. $modeldel = new leadsdeletedby;
  3462. $modeldel->id='';
  3463. $modeldel->startdate=@$startDate;
  3464. $modeldel->enddate=@$endDate;
  3465. $modeldel->data=$alldeletedIds;
  3466. $modeldel->deletedOn=time();
  3467. $modeldel->deletedBy=Yii::app()->session->get('userName');
  3468. $modeldel->deletedById=Yii::app()->session->get('id');
  3469. /* $modeldel->setAttributes(array(
  3470. 'id' => '', //additional data you want to insert
  3471. 'startdate' => @$startDate, //additional
  3472. 'enddate' => @$endDate, //additional
  3473. 'data' => 'sdfsdf', //additional
  3474. 'deletedOn' => time(), //additional
  3475. 'deletedBy' => Yii::app()->session->get('userName'), //additional
  3476. 'deletedById' =>Yii::app()->session->get('id'), //additional //additional
  3477. ));*/
  3478. $modeldel->save();
  3479. $this->redirect(Yii::app()->request->urlReferrer);
  3480. }
  3481. public function actionuser_monthly_report() {
  3482. $this->render('user_monthly_report');
  3483. }
  3484. public function actionuser_login_report() {
  3485. $this->render('user_login_report');
  3486. }
  3487. public function actiondownload_login_report() {
  3488. $limitvalue = @$_REQUEST['fetchrecordsBydropdown'];
  3489. $userid = @$_REQUEST['User']['id'];
  3490. if(isset($limitvalue) && !empty($limitvalue) && isset($userid) && !empty($userid)){
  3491. $paginationExcelValue = @$_POST['fetchrecordsBydropdown'];
  3492. if(isset($paginationExcelValue) && !empty($paginationExcelValue)){
  3493. $explodedpaginationValue = explode('-',$paginationExcelValue);
  3494. $startLimit = $explodedpaginationValue[0];
  3495. $endLimit = 10000;
  3496. } else {
  3497. $startLimit = '';
  3498. $endLimit = '';
  3499. }
  3500. if(isset($startLimit) && isset($endLimit) && !empty($endLimit)){
  3501. $limitCond = " limit $startLimit , $endLimit";
  3502. } else {
  3503. $limitCond = '';
  3504. }
  3505. //Here is the code to set conditions for fetch records from database
  3506. $condfilter = '';
  3507. if(isset($userid) && !empty($userid))
  3508. {
  3509. if(isset($userid) && !empty($userid))
  3510. {
  3511. $condfilter .= "t.userid = ".$userid." AND ";
  3512. }
  3513. if(isset($condfilter) && !empty($condfilter)){
  3514. $wherecon = "WHERE ";
  3515. } else {
  3516. $wherecon = "";
  3517. }
  3518. $data=Yii::app()->db->createCommand("select t.userId,t.userName,t.loginTime,t.type from userloginlog as t $wherecon $condfilter t.userId > 0 order by t.logId DESC $limitCond")->queryAll();
  3519. }else{
  3520. $data=0;
  3521. }
  3522. if(count($data)>0){
  3523. $file_name = "lms" . "_" . date("Y-m-d_H-i", time()) . ".csv";
  3524. header('Content-Type: text/html; charset=utf-8');
  3525. header("Content-type: application/octet-stream");
  3526. header("Content-Disposition: attachment; filename=\"$file_name\"");
  3527. header("Cache-Control: cache, must-revalidate");
  3528. header("Pragma: public");
  3529. $col = array(
  3530. 'SNO.','User Name','loginTime');
  3531. foreach ($col as $key => $value) {
  3532. echo $value . ",";
  3533. }
  3534. echo "\n";
  3535. $i=1;
  3536. foreach ($data as $key => $value) {
  3537. $loginTime = date("d M Y H:i:s A",$value['loginTime']);
  3538. echo $i++ . ",";
  3539. echo @$value["userName"] . ",";
  3540. echo @$loginTime . ",";
  3541. echo "\n";
  3542. }
  3543. }
  3544. else{
  3545. $this->redirect('index.php?r=leads/user_login_report');
  3546. //$dataProvider=new CActiveDataProvider('LeadReport', array('criteria'=>@$criteria,));
  3547. //$this->render('reports',array('model'=>$model,'dataProvider'=>$dataProvider));
  3548. }
  3549. } else {
  3550. $this->render('user_login_report');
  3551. }
  3552. }
  3553. public static function getMTD($leadStatusId){
  3554. $CurrentMonth_first_minute = mktime(0, 0, 0, date("n"), 1);
  3555. $CurrentMonth_last_minute = mktime(23, 59, 0, date("n"), date("t"));
  3556. $sql = "select count(leadId) as total from lead l join user u on u.id=l.currentAllocatedId where l.leadStatusId = ".@$leadStatusId." and (l.updatedOn between '".@$CurrentMonth_first_minute."' and '".@$CurrentMonth_last_minute."') and u.status='Active' limit 1 ";
  3557. $count=Yii::app()->db->createCommand($sql)->queryColumn();
  3558. echo @$count[0];
  3559. //echo Lead::model()->count(array("select"=>'leadid',"condition"=>" leadStatusId = ".@$leadStatusId.""));
  3560. }
  3561. public static function getYTD($leadStatusId){
  3562. $CurrentYear_first_minute = mktime(0, 0, 0, 1, 1, date('Y'));
  3563. $CurrentYear_last_minute = mktime(0, 0, 0, 13, 0, date('Y'));
  3564. $sql = "select count(leadId) as total from lead l join user u on u.id=l.currentAllocatedId where l.leadStatusId = ".@$leadStatusId." and (l.updatedOn between '".@$CurrentYear_first_minute."' and '".@$CurrentYear_last_minute."') and u.status='Active' ";
  3565. $count=Yii::app()->db->createCommand($sql)->queryColumn();
  3566. //echo Lead::model()->count(array("select"=>'leadid',"condition"=>" leadStatusId = ".@$leadStatusId.""));
  3567. echo @$count[0];
  3568. }
  3569. public static function getUniqueMobLeadCountByStatus($leadStatusId){
  3570. if(isset($leadStatusId) && !empty($leadStatusId)){
  3571. $todayexpiryDate= date('d-M-Y',time());
  3572. $nontydaystime=strtotime("-90 days",strtotime($todayexpiryDate));
  3573. $date1Filer = @$_REQUEST['Lead']['createdOn'];
  3574. $date2Filer = @$_REQUEST['Lead']['createdOn2'];
  3575. $leadFilter = @$_REQUEST['LeadSourceMaster']['leadSourceId'];
  3576. $filterCond ='';
  3577. if(isset($leadFilter) && !empty($leadFilter)){
  3578. $filterCond .= " AND l.leadSourceId = ".$leadFilter."";
  3579. }
  3580. if(isset($date1Filer) && !empty($date1Filer) && isset($date2Filer) && !empty($date2Filer)){
  3581. $date1Filer = strtotime($date1Filer);
  3582. $date2Filer = strtotime($date2Filer);
  3583. $filterCond .= " AND l.createdOn >= ".$date1Filer." and l.createdOn <= ".$date2Filer."";
  3584. }
  3585. if(Yii::app()->session->get('type')=='superadmin'){
  3586. //$sql = "select mobile from lead l where l.leadStatusId=".$leadStatusId." $filterCond ";
  3587. $sql = "select count(l.mobile) as totalunique from lead l where l.leadStatusId=".$leadStatusId." and l.leadStatusId != 10 $filterCond group by l.leadStatusId ";
  3588. } else {
  3589. $impresuser = DashboardController::implodeResult(Yii::app()->session['relationalManager']);
  3590. $sql = "select count(l.mobile) as totalunique from lead l where l.leadStatusId=".$leadStatusId." and l.leadStatusId != 10 and l.currentAllocatedId IN (".@$impresuser.") $filterCond group by l.leadStatusId ";
  3591. }
  3592. //echo $res = Lead::model()->count(array("select"=>"count(distinct mobile) as totalunique","condition"=>" leadStatusId=".$leadStatusId." $filterCond "));
  3593. //$count=Yii::app()->db->createCommand($sql)->queryScalar();
  3594. $count=Yii::app()->db->createCommand($sql)->queryScalar();
  3595. /*$criteria = new CDbCriteria();
  3596. $criteria->select = "mobile";
  3597. $criteria->condition = " leadStatusId=".$leadStatusId."";
  3598. $count=Lead::model()->findAll($criteria);*/
  3599. //echo count($count);
  3600. echo @$count?@$count:0;
  3601. } else {
  3602. echo 0;
  3603. }
  3604. //echo Lead::model()->count(array("select"=>'leadid',"condition"=>" leadStatusId = ".@$leadStatusId.""));
  3605. }
  3606. public function actiondownload_monthly_report(){
  3607. $selectedMonth = @$_REQUEST['selectedMonth'];
  3608. if(Yii::app()->session->get('type')=='superadmin' or Yii::app()->session->get('roleId')==4){
  3609. $userId = @$_REQUEST['User']['id'];
  3610. } else {
  3611. $userId = Yii::app()->session->get('id');
  3612. }
  3613. $startmonthTime = @$_REQUEST['startTime_'.$selectedMonth];
  3614. $endMonthTime = @$_REQUEST['endtime_'.$selectedMonth];
  3615. $wherecon = "t.updatedOn >= ".$startmonthTime." and t.updatedOn <= ".$endMonthTime." and t.currentAllocatedId=".@$userId." ";
  3616. if(empty($startmonthTime) or empty($endMonthTime)){
  3617. $data = array();
  3618. } else {
  3619. $sqlquery = "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.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 $wherecon and t.leadId > 0 order by t.leadId DESC limit 0,10000";
  3620. $data=Yii::app()->db->createCommand($sqlquery)->queryAll();
  3621. }
  3622. if(count($data)>0){
  3623. $file_name = "lmsmonthlyreport" . "_" .$userId. date("Y-m-d_H-i", time()) . ".csv";
  3624. header('Content-Type: text/html; charset=utf-8');
  3625. header("Content-type: application/octet-stream");
  3626. header("Content-Disposition: attachment; filename=\"$file_name\"");
  3627. header("Cache-Control: cache, must-revalidate");
  3628. header("Pragma: public");
  3629. $col = array(
  3630. 'SNO.','Name','Mobile Number',' Email Id','Address','City','State','Members','Premium','Product Details','Lead Status','Status','isJunk','Lead Source','Lead Stage','Lead Description','Activity Description','Customer Type','Product Name','Policy Type','Plan Type','Campaign Name','UTM Code','Owner','Last Modified Date','Agent-Id'
  3631. );
  3632. foreach ($col as $key => $value) {
  3633. echo $value . ",";
  3634. }
  3635. echo "\n";
  3636. $i=1;
  3637. foreach ($data as $key => $value) {
  3638. if($value['currentAllocatedId']==$value['createdBy']){
  3639. $owner = $value['firstName']." ".$value['lastName']."(C)";
  3640. } else {
  3641. if(isset($value['firstName']) && !empty($value['firstName'])){
  3642. $owner = $value['firstName']." ".$value['lastName'];
  3643. } else {
  3644. $owner = "NA";
  3645. }
  3646. }
  3647. if(isset($value['updatedOn']) && !empty($value['updatedOn'])){
  3648. $strtme = date("d M Y H:i:s A",$value['updatedOn']);
  3649. } else{ $strtme = 'NA'; }
  3650. $lastModifieddate = $strtme;
  3651. $sqlDesc = "select group_concat(description) as ActivityDescription from leadFollowup where leadId=".@$value["leadId"]." ";
  3652. $dataDesc=Yii::app()->db->createCommand($sqlDesc)->queryAll();
  3653. $leadActivity = @$dataDesc[0]['ActivityDescription']?stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$dataDesc[0]['ActivityDescription'])):'';
  3654. echo $i++ . ",";
  3655. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ", @$value["name"])) . ",";
  3656. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value["mobile"])) . ",";
  3657. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$value["email"])) . ",";
  3658. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$value["address"])) . ",";
  3659. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$city)) . ",";
  3660. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$state)) . ",";
  3661. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value["members"])) . ",";
  3662. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value["premium"])) . ",";
  3663. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value['productDetails'])) . ",";
  3664. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value['leadStatus'])) . ",";
  3665. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value['status'])) . ",";
  3666. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value['isJunk'])) . ",";
  3667. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value['leadSourceTitle'])) . ",";
  3668. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9\'-]|'$/", " ",@$value['leadStage'])) . ",";;
  3669. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$value["leadDescription"])) . ",";
  3670. echo @$leadActivity . ",";
  3671. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$value["customerType"])) . ",";
  3672. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$value["productName"])) . ",";
  3673. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$value["policyType"])) . ",";
  3674. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$value["planType"])) . ",";
  3675. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$value["campaignName"])) . ",";
  3676. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$value["leadSourceCode"])) . ",";
  3677. echo @$owner . ",";
  3678. echo @$lastModifieddate . ",";
  3679. echo stripslashes(preg_replace("/^'|[^A-Za-z0-9@._\'-]|'$/", " ",@$value["ws_agentid"])) . ",";
  3680. echo "\n";
  3681. }
  3682. } else {
  3683. Yii::app()->user->setFlash('msg','No Record Found');
  3684. $this->render('user_monthly_report');
  3685. }
  3686. }
  3687. //Lead Assignment without page refresh
  3688. public function actionAllocateLeadsByAjax(){
  3689. $Id = $_REQUEST['userids'];
  3690. $teamId = @$_REQUEST['Team']['teamId'];
  3691. $userId = $_REQUEST['Team']['teamMemberId'];
  3692. $updatedBy = @$_SESSION['id'];
  3693. $actionurl = @$_REQUEST['actionurl'];
  3694. $paginationsize = Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize'])?Yii::app()->user->getState('pageSize',Yii::app()->params['defaultPageSize']):25;
  3695. $userdetails=Yii::app()->db->createCommand("select firstName,lastName from user where id=".$userId." ")->queryAll();
  3696. $myArray = array();
  3697. $responseAll =array();
  3698. $t=0;
  3699. foreach($Id as $key=>$value){
  3700. $model = new AllocatedLeads();
  3701. $model->scenario = 'AllocatedLeads';
  3702. $model->setAttributes(array(
  3703. 'currentAllocatedDate' => time(), //additional data you want to insert
  3704. 'createdOn' => time(), //additional data you want to insert
  3705. 'updatedOn' => time(), //additional
  3706. 'updatedBy' => @$updatedBy, //additional
  3707. 'createdBy' => @$updatedBy, //additional
  3708. 'leadStatusId' => '35', //additional //additional
  3709. ));
  3710. $leadId = @$value;
  3711. $model->leadId = @$value;
  3712. $model->userId = @$userId;
  3713. $model->teamId = @$teamId;
  3714. //echo @$teamId.' - '.@$userId.' - '.@$leadId;
  3715. $model->allocatedId = null;
  3716. $model->isNewRecord = true;
  3717. $model->save();
  3718. $model=new Lead();
  3719. $model->scenario = 'Lead';
  3720. $updatedOn = time();
  3721. Lead::model()->updateByPk(@$value, array('currentAllocatedId'=>@$userId,'leadStatusId'=>'35','updatedBy'=>@$updatedBy,'updatedOn'=>@$updatedOn,'currentAllocatedDate'=>@$updatedOn));
  3722. $responseAll[$t]['ownername'] = $userdetails[0]['firstName']." ".$userdetails[0]['lastName'];
  3723. $responseAll[$t]['classname'] = "owner_".@$value;
  3724. $responseAll[$t]['rowclass'] = @$value;
  3725. $myArray[0][$t]=$responseAll[$t];
  3726. $myArray[1]['roleId']=Yii::app()->session->get('roleId');
  3727. $myArray[2]['actionurl']=$actionurl;
  3728. $myArray[3]['paginationsize']=$paginationsize;
  3729. $t++;
  3730. }
  3731. $red = @$_REQUEST['red'];
  3732. if(Yii::app()->request->isAjaxRequest)
  3733. {
  3734. if(Yii::app()->session->get('type')=='superadmin'){
  3735. //print_r($myArray); die;
  3736. //echo "superadmin".$userdetails[0]['firstName'].$userdetails[0]['lastName'];
  3737. echo json_encode($myArray);
  3738. } else if(Yii::app()->session->get('roleId')==4 or Yii::app()->session->get('isAllocator')=='yes') {
  3739. echo json_encode($myArray);
  3740. } else {
  3741. $myArray=array('somethingwrong');
  3742. echo json_encode($myArray);
  3743. }
  3744. exit;
  3745. }
  3746. if($this->action->id=='AllocateLeads' && $red == 1)
  3747. {
  3748. $this->redirect(array('leads/lead_list'));
  3749. }
  3750. $this->redirect(array('leads/fresh_leads'));
  3751. }
  3752. public function actiongetLeadStagesIds(){
  3753. $leadStageId=@$_REQUEST['leadStageId'];
  3754. $mobile=@$_REQUEST['mobile'];
  3755. $leadid=@$_REQUEST['leadid'];
  3756. $agentIds=Yii::app()->db->createCommand("select group_concat(distinct leadStageMaster.leadStage) as leadStage,count(distinct lead.leadStageId) as total from lead left join leadStageMaster on leadStageMaster.leadStageId=lead.leadStageId where lead.mobile='".@$mobile."' and lead.leadStageId!='' order by lead.leadId desc ")->queryAll();
  3757. //$displayedSyage=Yii::app()->db->createCommand("select leadStage from leadStageMaster where leadStageId='".@$leadStageId."' ")->queryAll();
  3758. if( $agentIds[0]['total'] >= 1){
  3759. echo @$agentIds[0]['leadStage'];
  3760. } else {
  3761. echo "";
  3762. }
  3763. //echo explode(',',$agentId);
  3764. }
  3765. public function actiongetAgentIds(){
  3766. $ws_agentid=@$_REQUEST['ws_agentid'];
  3767. $mobile=@$_REQUEST['mobile'];
  3768. echo $leadid=@$_REQUEST['leadid'];
  3769. //$agentIds=Yii::app()->db->createCommand("select group_concat(distinct ws_agentid) as ws_agentid,count(distinct ws_agentid) as total from lead where mobile='".@$mobile."' and ws_agentid!='' order by leadId desc ")->queryAll();
  3770. $sqlQuery = "SELECT DISTINCT ws_agentid FROM lead WHERE mobile='".@$mobile."' AND ws_agentid!='' ORDER BY leadId DESC LIMIT 5";
  3771. $allAgentId = Yii::app()->db->createCommand($sqlQuery)->queryAll();
  3772. $agentArray = array();
  3773. foreach($allAgentId as $id)
  3774. {
  3775. $agentArray[] = $id['ws_agentid'];
  3776. }
  3777. if($agentArray != array())
  3778. {
  3779. echo implode(', ', $agentArray);
  3780. }
  3781. else
  3782. {
  3783. echo '';
  3784. }
  3785. exit;
  3786. }
  3787. public static function updateLeadAllCount($leadStatusId)
  3788. {
  3789. if(BaseController::getConfigurationValue('leadallcount'))
  3790. {
  3791. $loggedInUserId = Yii::app()->session->get('id');
  3792. $createdYear = date('Y');
  3793. $createdMonth = date('m');
  3794. $createdOn = time();
  3795. $userRole = Yii::app()->session->get('roleId');
  3796. Yii::app()->db->createCommand('START TRANSACTION;')->execute();
  3797. if ($userRole == 3 || $userRole == 4)
  3798. {
  3799. if ($leadStatusId == 34)
  3800. {
  3801. $leadStatusId = 35;
  3802. }
  3803. Yii::app()->db->createCommand("update leadallcount set count = count + 1,
  3804. createdOn = $createdOn, createdBy = $loggedInUserId, updatedOn = $createdOn, updatedBy = $loggedInUserId
  3805. where userid = 1 && accesskey = '$createdYear-$createdMonth' && leadtype = $leadStatusId")->execute();
  3806. Yii::app()->db->createCommand("update leadallcount set count = count + 1,
  3807. createdOn = $createdOn, createdBy = $loggedInUserId, updatedOn = $createdOn, updatedBy = $loggedInUserId
  3808. where userid = 1 && accesskey = '$createdYear' && leadtype = $leadStatusId")->execute();
  3809. }
  3810. Yii::app()->db->createCommand("update leadallcount set count = count + 1,
  3811. createdOn = $createdOn, createdBy = $loggedInUserId, updatedOn = $createdOn, updatedBy = $loggedInUserId
  3812. where userid = $loggedInUserId && accesskey = '$createdYear-$createdMonth' && leadtype = $leadStatusId")->execute();
  3813. Yii::app()->db->createCommand("update leadallcount set count = count + 1,
  3814. createdOn = $createdOn, createdBy = $loggedInUserId, updatedOn = $createdOn, updatedBy = $loggedInUserId
  3815. where userid = $loggedInUserId && accesskey = '$createdYear' && leadtype = $leadStatusId")->execute();
  3816. Yii::app()->db->createCommand('COMMIT;')->execute();
  3817. }
  3818. }
  3819. /**
  3820. * SearchLeadList based on mobile/name/email on lead lists.
  3821. * @param string $searchParameter
  3822. * @see *_lead_list.php.
  3823. * @return string
  3824. */
  3825. public static function searchLeadList($searchParameter)
  3826. {
  3827. //$searchParameter = @trim($_REQUEST['mob_name_email_search']);
  3828. $cond = '';
  3829. if(is_numeric($searchParameter))
  3830. {
  3831. if(strlen($searchParameter) == 10)
  3832. {
  3833. //$cond = " AND mobile = " . $searchParameter;
  3834. $cond = " AND mobile = '$searchParameter'";
  3835. }
  3836. if(strlen($searchParameter) < 10)
  3837. {
  3838. if(strlen($searchParameter) > 3)
  3839. {
  3840. if(strlen($searchParameter) > 5)
  3841. {
  3842. $cond = " AND mobile like '%" . $searchParameter . "%' ";
  3843. }
  3844. else
  3845. {
  3846. $cond = " AND concat(mobile,email) like '%" . $searchParameter . "%' ";
  3847. }
  3848. }
  3849. }
  3850. }
  3851. else
  3852. {
  3853. if(strlen($searchParameter) > 2)
  3854. {
  3855. if(strpos($searchParameter, '@') || strpos($searchParameter, '_'))
  3856. {
  3857. $cond = " AND email like '%" . @trim($searchParameter) . "%' ";
  3858. }
  3859. else if(strpos($searchParameter, ' '))
  3860. {
  3861. $cond = " AND name like '%" . $searchParameter . "%' ";
  3862. }
  3863. else
  3864. {
  3865. $cond = " AND concat(name,email) like '%" . $searchParameter . "%' ";
  3866. }
  3867. }
  3868. }
  3869. return $cond;
  3870. }
  3871. }