Subversion Repositories SmartDukaan

Rev

Rev 19121 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | RSS feed

<?php
App::uses('AppController', 'Controller');
/**
 * NotificationCampaigns Controller
 *
 * @property NotificationCampaign $NotificationCampaign
 * @property PaginatorComponent $Paginator
 */
class NotificationCampaignsController extends AppController {

/**
 * Components
 *
 * @var array
 */
        public $components = array('Paginator');

        public function beforeFilter() {                
                parent::beforeFilter();
                $this->Auth->allow('notificationactive');
                $this->apihost = Configure::read('pythonapihost');
        }

/**
 * admin_index method
 *
 * @return void
 */
        public function admin_index() {
                
                $page = $this->request->query('page');
                if(!isset($page)){
                        $page = 1;
                }
                $limit = 20;
                $offset = ($page - 1)*$limit;
                $url = Configure::read('nodeurl')."/getLatestNotificationCampaigns/?notification_type=GENERAL_NOTIFICATION&offset=".$offset."&limit=".$limit;
//              echo $url;
                $response = $this->make_request($url,null);
                $NotificationCampaign = array();
                $newNotification = array();
                $checkArray=array();
                $id_set = '';

                        foreach ($response['result'] as $key => $value) {
                                if($id_set == '')
                                {
                                        $id_set = $value['_id'];
                                }
                                else
                                {
                                        $id_set = $id_set.','.$value['_id'];
                                }
                                $newNotification[$key]["NotificationCampaign"] = $value;
                                $newNotification[$key]["NotificationCampaign"]["id"] = $value["_id"];
                                $newNotification[$key]["NotificationCampaign"]["expiresat"] = date('Y-m-d H:i:s', $value["expiresat"]/1000);
                                $newNotification[$key]["NotificationCampaign"]["created"] = date('Y-m-d H:i:s', $value["created"]/1000);
//                              unset($value["_id"]);
                        }
                $url = Configure::read('nodeurl')."/getPushNotificationsStats/?campaigns=".$id_set;
//              echo $url;
                $result = $this->make_request($url,null);
//              echo "Before Modification";
//              debug($result);
                
//              Logic for new result start
                
                foreach ($result as $notkey =>$notval){
                        
                                $total = 0;
                                $total_open = 0;
                                $total_rec = 0;
                                $success = 0;
                                if(isset($notval["recieved"]))
                                {
                                        $total = $notval["recieved"] + $total;
                                        $total_rec = $notval["recieved"];
                                }
                                        
                                if(isset($notval["expired"]))
                                {
                                        $total = $notval["expired"] + $total;
                                }
                                        
                                if(isset($notval["opened"]))
                                {
                                        $total = $notval["opened"] + $total;
                                        $total_rec = $total_rec + $notval["opened"];
                                        $total_open = $notval["opened"];
                                }
                                
                                if(isset($notval["failed"]))
                                {
                                        $total = $notval["failed"] + $total;
                                }
                                
                                if(isset($notval["sent"]))
                                {
                                        $total = $notval["sent"] + $total;
                                }
                                
                                $success = $total;
                                
                                if(isset($notval["failed"]))
                                {
                                        $success = $total - $notval["failed"] ;
                                }
                                
                                if(isset($notval["referrer"]))
                                {
                                        $total_open = $notval["referrer"] + $total_open;
                                }
                                
                                if(isset($notval["login"]))
                                {
                                        $total_open = $notval["login"] + $total_open;
                                }
                                
                                $result[$notkey]["opened"] = $total_open;
                                $result[$notkey]["recieved"] = $total_rec;
                                $result[$notkey]["total"] = $total;
                                $result[$notkey]["success"] = $success;
                                
                        
//                      if(isset($notval["recieved"])&& isset($notval["opened"])){
//                              $result[$notkey]["recieved"] = $notval["opened"] + $notval["recieved"];

//                      }
                        
//                      if(isset($notval["opened"]))
//                      {
//                              $total_open = $notval["opened"];
//                              if(isset($notval["referrer"]))
//                              {
//                                      $total_open = $notval["referrer"] + $total_open;
//                              }
                                
//                              if(isset($notval["login"]))
//                              {
//                                      $total_open = $notval["login"] + $total_open;
//                              }
//                              $result[$notkey]["opened"] = $total_open;
//                      }
                        
//                      $result[$notkey]["opened"] = $notval["login"] + $notval["expired"] + $notval["opened"] +$notval['recieved'];
                        
                }
//              echo "After Modification";
//              debug($result);
                        
//              Logic end
                
                // echo "Idset", $id_set;
                // debug($result);
                // $campaign_array = array();
                // foreach ($vari as $key => $value) {
                //      echo $value['NotificationCampaign']['id'];

                // }
                /*
                foreach ($vari as $key => $value) {
                        $cid=$value['NotificationCampaign']['id'];
                        $sqlQuery = "SELECT status as status,notification_campaign_id,type,count(*) as count FROM pushnotifications group by notification_campaign_id, type,status";
                        #$successQuery="SELECT count(*) as count from pushnotifications where status=1 and type='sent' and notification_campaign_id=$cid";
                        $successQuery="SELECT count(distinct p.user_id) as count from pushnotifications p join devices d on p.user_id=d.user_id where status=1 and type='sent' and notification_campaign_id='$cid'  and d.versioncode>=14";
                        $resul=$this->NotificationCampaign->query($sqlQuery);   
                        $success_result=$this->NotificationCampaign->query($successQuery);      
                        array_push($checkArray, $success_result[0][0]['count']);
                }
                // debug($checkArray);
                $finalResult = array();
                foreach ($resul as $key => $value) {
                        $finalResult[$value['pushnotifications']['notification_campaign_id']][$value['pushnotifications']['type']]=$value[0]['count'];
                        $finalResult[$value['pushnotifications']['notification_campaign_id']][$value['pushnotifications']['status']]=$value[0]['count'];
                        //$finalResult[$value['pushnotifications']['notification_campaign_id']][$value['pushnotifications']['type']]=$value[0]['status'];                       
                }
                // debug($finalResult);
                */
                // $this->set('notificationWithVersionCode', $checkArray);
                $this->set('notificationCampaigns', $newNotification);
                //$this->set('notificationCampaignsCount', $finalResult);
                $this->set(compact('result','page'));
        }

        public function admin_batchcredit() {

                $page = $this->request->query('page');
                if(!isset($page)){
                        $page = 1;
                }
                $limit = 20;
                $offset = ($page - 1)*$limit;
                $url = Configure::read('nodeurl')."/getLatestNotificationCampaigns/?notification_type=BATCH_CREDIT&offset=".$offset."&limit=".$limit;
                $response = $this->make_request($url,null);
                $NotificationCampaign = array();
                $newNotification = array();
                $checkArray=array();
                $id_set = '';
        
                                foreach ($response['result'] as $key => $value) {
                                        if($id_set == '')
                                        {
                                                $id_set = $value['_id'];
                                        }
                                        else
                                        {
                                                $id_set = $id_set.','.$value['_id'];
                                        }
                                        $newNotification[$key]["NotificationCampaign"] = $value;
                                        $newNotification[$key]["NotificationCampaign"]["id"] = $value["_id"];
                                        $newNotification[$key]["NotificationCampaign"]["expiresat"] = date('Y-m-d H:i:s', $value["expiresat"]/1000);
                                        $newNotification[$key]["NotificationCampaign"]["created"] = date('Y-m-d H:i:s', $value["created"]/1000);
                                }
                        
                                $url = Configure::read('nodeurl')."/getPushNotificationsStats/?campaigns=".$id_set;
                                $result = $this->make_request($url,null);
                
                                //              Logic for new result start
                
                                foreach ($result as $notkey =>$notval){
                                                
                                        $total = 0;
                                        $total_open = 0;
                                        $total_rec = 0;
                                        $success = 0;
                                        if(isset($notval["recieved"]))
                                        {
                                                $total = $notval["recieved"] + $total;
                                                $total_rec = $notval["recieved"];
                                        }
                                                
                                        if(isset($notval["expired"]))
                                        {
                                                $total = $notval["expired"] + $total;
                                        }
                                                
                                        if(isset($notval["opened"]))
                                        {
                                                $total = $notval["opened"] + $total;
                                                $total_rec = $total_rec + $notval["opened"];
                                                $total_open = $notval["opened"];
                                        }
                
                                        if(isset($notval["failed"]))
                                        {
                                                $total = $notval["failed"] + $total;
                                        }
                
                                        if(isset($notval["sent"]))
                                        {
                                                $total = $notval["sent"] + $total;
                                        }
                
                                        $success = $total;
                
                                        if(isset($notval["failed"]))
                                        {
                                                $success = $total - $notval["failed"] ;
                                        }
                
                                        if(isset($notval["referrer"]))
                                        {
                                                $total_open = $notval["referrer"] + $total_open;
                                        }
                
                                        if(isset($notval["login"]))
                                        {
                                                $total_open = $notval["login"] + $total_open;
                                        }
                
                                        $result[$notkey]["opened"] = $total_open;
                                        $result[$notkey]["recieved"] = $total_rec;
                                        $result[$notkey]["total"] = $total;
                                        $result[$notkey]["success"] = $success;                                 
                                }                                       
                                //              Logic end
                
                                $this->set('notificationCampaigns', $newNotification);
                                //$this->set('notificationCampaignsCount', $finalResult);
                                $this->set(compact('result','page'));
                }
        
        
        
/**
 * admin_view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function admin_view($id = null) {
                $url = Configure::read('nodeurl')."/getNotificationCampaignById?id=".$id;
                $result = $this->make_request($url,null);
                $getdata = array();
                $getdata["NotificationCampaign"] = $result;
                $getdata["NotificationCampaign"]["expiresat"] = date('Y-m-d H:i:s', $result["expiresat"]/1000);
                $getdata["NotificationCampaign"]["created"] = date('Y-m-d H:i:s', $result["created"]/1000);
                unset($getdata["NotificationCampaign"]["_id"]);
//              debug($getdata);
                
//              if (!$this->NotificationCampaign->exists($id)) {
//                      throw new NotFoundException(__('Invalid notification campaign'));
//              }
//              $sort = $this->request->query('type');
//              $direction = $this->request->query('order');
//              $options = array('conditions' => array('NotificationCampaign.' . $this->NotificationCampaign->primaryKey => $id));
//              $userData=$this->NotificationCampaign->find('first', $options);
//              debug($userData);
                // $userActions = array();
                // foreach ($userData['Pushnotification'] as $key => $value) {
                //      if($value['type']=='sent'){
                //      $userActions[$value['user_id']][$value['type']] = $value['created'];
                //      $userActions[$value['user_id']]['status'] =$value['status'];
                //      }else{
                //              $userActions[$value['user_id']][$value['type']] = $value['response_time'];
                //      }
                //       //debug($value);
                // }

                $userActions = array();
                $url = Configure::read('nodeurl')."/getPushNotificationByCampaignId/?notification_campaign_id=".$id;
                // echo $url;
                $result = $this->make_request($url,null);
                foreach ($result as $key => $value) {
                        /*if($value['type']=='sent'){
                                $epoch = $value['created']/1000;
                                $dt = date('Y-m-d H:i:s', $epoch);
                                // echo $dt->format('Y-m-d H:i:s');
                                $userActions[$value['user_id']][$value['type']] = $dt;//$value['created'];
                                $userActions[$value['user_id']]['status'] =$value['status'];
                        }else if(isset($value['response_time'])){
                                $epoch = $value['response_time']/1000;
                                $dt = date('Y-m-d H:i:s', $epoch);
                                if(isset($value['user_id'])){
                                        $userActions[$value['user_id']][$value['type']] = $dt;//$value['response_time'];
                                }
                        }else{
                                $epoch = $value['created']/1000;
                                $dt = date('Y-m-d H:i:s', $epoch);
                                if(isset($value['user_id'])){
                                        $userActions[$value['user_id']][$value['type']] = $dt;//$value['response_time'];
                                }
                        }*/
                        if($value['sent_timestamp']!=null){
                                $epoch = $value['sent_timestamp']/1000;
                                $dt = date('Y-m-d H:i:s', $epoch);
                                $userActions[$value['user_id'].'_'.$value['_id']]['sent'] = $dt;
                        }
                        if($value['receive_timestamp']!=null){
                                $epoch = $value['receive_timestamp']/1000;
                                $dt = date('Y-m-d H:i:s', $epoch);
                                $userActions[$value['user_id'].'_'.$value['_id']]['recieved'] = $dt;
                        }
                        if($value['open_timestamp']!=null){
                                $epoch = $value['open_timestamp']/1000;                 
                                $dt = date('Y-m-d H:i:s', $epoch);
                                $userActions[$value['user_id'].'_'.$value['_id']]['opened'] = $dt;
                        }               
                }

//              $cid=$userData['NotificationCampaign']['id'];
//              $sqlQuery = "SELECT status as status,notification_campaign_id,type,count(*) as count FROM pushnotifications where notification_campaign_id=4120 group by type,status";
//              $resul=$this->NotificationCampaign->query($sqlQuery);   
//              debug($resul);
//              $finalResult = array(); 
//              foreach ($resul as $key => $value) {
//                      $finalResult[$value['pushnotifications']['notification_campaign_id']][$value['pushnotifications']['type']]=$value[0]['count'];
//                      $finalResult[$value['pushnotifications']['notification_campaign_id']][$value['pushnotifications']['status']]=$value[0]['count'];
//                      //$finalResult[$value['pushnotifications']['notification_campaign_id']][$value['pushnotifications']['type']]=$value[0]['status'];                       
//              }
                
                $this->set('notificationData', $getdata);
                $this->set('notificationCampaign', $userActions);
//              $this->set('notificationCount', $finalResult);
        }

/**
 * admin_add method
 *
 * @return void
 */
        public function admin_add() {
                if ($this->request->is('post')) {
                        $this->NotificationCampaign->create();
                        if ($this->NotificationCampaign->save($this->request->data)) {
                                $this->Session->setFlash(__('The notification campaign has been saved.'));
                                return $this->redirect(array('action' => 'index'));
                        } else {
                                $this->Session->setFlash(__('The notification campaign could not be saved. Please, try again.'));
                        }
                }
        }

/**
 * admin_edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function admin_edit($id = null) {
//              if (!$this->NotificationCampaign->exists($id)) {
//                      throw new NotFoundException(__('Invalid notification campaign'));
//              }
                if ($this->request->is(array('post', 'put'))) {
                        $message= $this->request->data['NotificationCampaign'];
                        if($message['expiresat']['meridian']=='pm'){
                                $message['expiresat'] = 1000*mktime(($message['expiresat']['hour'])+12,$message['expiresat']['min'],0,$message['expiresat']['month'],$message['expiresat']['day'],$message['expiresat']['year']);
                        }else{
                                $message['expiresat'] = 1000*mktime($message['expiresat']['hour'],$message['expiresat']['min'],0,$message['expiresat']['month'],$message['expiresat']['day'],$message['expiresat']['year']);
                        }
//                      $senddata = '{"id":"56d80b7514fb6c4a5183a74a","name":"Naman","title":"Naman","message":"Naman","type":"url","url":"http:\/\/api.profittill.com","expiresat":1344988800000,"status":"active","sendsms":0,"messagetext":"","smsprocessed":0}';
//                      debug($message);
                        $url = Configure::read('nodeurl')."/updatedNotificationCampaign";//remove hardcoded value
                        $debres = $this->make_request($url,json_encode($message,JSON_NUMERIC_CHECK));
//                      debug($debres);
                        
//                      if ($this->NotificationCampaign->save($this->request->data)) {
                        if($debres['message'] == 'Success'){
                                $this->Session->setFlash(__('The notification campaign has been saved.'));
                                return $this->redirect(array('action' => 'index'));
                        } else {
                                $this->Session->setFlash(__('The notification campaign could not be saved. Please, try again.'));
                        }
                } else {
//                      $options = array('conditions' => array('NotificationCampaign.' . $this->NotificationCampaign->primaryKey => $id));
//                      $this->request->data = $this->NotificationCampaign->find('first', $options);
                        $url = Configure::read('nodeurl')."/getNotificationCampaignById?id=".$id;
                        $result = $this->make_request($url,null);                       
                        $getdata = array();
                        $getdata["NotificationCampaign"] = $result;
                        $getdata["NotificationCampaign"]["expiresat"] = date('Y-m-d H:i:s', $result["expiresat"]/1000);
                        $getdata["NotificationCampaign"]["id"] =  $result["_id"];
                        unset($getdata["NotificationCampaign"]["_id"]);
                        $this->request->data = $getdata;
                }
        }

/**
 * admin_delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function admin_delete($id = null) {
                $this->NotificationCampaign->id = $id;
                if (!$this->NotificationCampaign->exists()) {
                        throw new NotFoundException(__('Invalid notification campaign'));
                }
                $this->request->onlyAllow('post', 'delete');
                if ($this->NotificationCampaign->delete()) {
                        $this->Session->setFlash(__('The notification campaign has been deleted.'));
                } else {
                        $this->Session->setFlash(__('The notification campaign could not be deleted. Please, try again.'));
                }
                return $this->redirect(array('action' => 'index'));
        }
        // $this->set(compact('result'));
        // 
        public function admin_show($id = null,$type=null,$status=null) {
                // $sqlQuery = "SELECT * FROM pushnotifications where notification_campaign_id=$id and type='$type' and status=$status" ;
                
                // $resul=$this->NotificationCampaign->query($sqlQuery1ry);
                // if($type == 0 || $type == 1)
                // {
                //      $type = "sent";
                // }
                // echo "type", $type;
                $url = Configure::read('nodeurl')."/getPushNotificationDetailsByType/?type=".$type."&notification_campaign_id=".$id."&status=".$status;//remove hardcoded value
                
                $result = $this->make_request($url,null);
                // debug($result);
//              $sqlQuery1 = "SELECT * FROM notification_campaigns where id=$id" ;
//              $resultData=$this->NotificationCampaign->query($sqlQuery1);
//              debug($resultData);
                $url = Configure::read('nodeurl')."/getNotificationCampaignById?id=".$id;
                $res = $this->make_request($url,null);
                debug($res);
                $getdata = array();
                if(!empty($res)){
                        $getdata["NotificationCampaign"] = $res;
                        $getdata["NotificationCampaign"]["expiresat"] = date('Y-m-d H:i:s', $res["expiresat"]/1000);
                        $getdata["NotificationCampaign"]["id"] =  $res["_id"];
                        unset($getdata["NotificationCampaign"]["_id"]);
                }
                
                
                

                $this->set(compact('result'));
                // $this->set('data', $result);
                $this->set('notificationData', $getdata);
        }

        public function admin_user($id = null) {
                $url = Configure::read('nodeurl')."/getPushNotificationByUserId/?user_id=".$id;
                $userdata = $this->make_request($url,null);
                // debug($userdata);
                $this->set(compact('userdata'));
                // $sqlQuery = "SELECT * FROM pushnotifications where user_id=$id order by id desc" ;
                // $resul=$this->NotificationCampaign->query($sqlQuery);
                // $this->set('userdata', $resul);
        }

        public function admin_sort($id = null) {
                $sort = $this->request->query('type');
                $direction = $this->request->query('order');
                //$cid = $this->request->query('cid');
                if($sort=='user_id'){
                        $sqlQuery = "SELECT * FROM pushnotifications where notification_campaign_id =$id order by $sort $direction" ;                   
                }
                else{
                        $sqlQuery = "SELECT * FROM pushnotifications where notification_campaign_id =$id order by type='$sort' $direction" ;
                }
                $resul=$this->NotificationCampaign->query($sqlQuery);
                $userActions = array();
                foreach ($resul as $key => $value) {
                        if($value['pushnotifications']['type']=='sent'){
                        $userActions[$value['pushnotifications']['user_id']][$value['pushnotifications']['type']] = $value['pushnotifications']['created'];
                        $userActions[$value['pushnotifications']['user_id']]['status'] =$value['pushnotifications']['status'];
                        }else{
                                $userActions[$value['pushnotifications']['user_id']][$value['pushnotifications']['type']] = $value['pushnotifications']['response_time'];
                        }                       
                }
                $this->set('notificationId',$id);
                $this->set('sortdata', $userActions);
        }

        public function notificationactive(){
                session_write_close();
                $cid = $this->request->query('cid');
                /*$cidVals = explode("_", $cid);
                $cid = $cidVals[0];
                $this->log("cid $cid",'notificationactive');
                $options = array('conditions' => array('id'=> $cid,'status'=>'active','expiresat >'=>date('Y-m-d H:i:s',time())),'recursive'=>-1);
                $count = $this->NotificationCampaign->find('count',$options);
                $this->log("count ".print_r($count,1),'notificationactive');
                if(!$count){
                        $result = array('success'=>false);
                }else{
                        $result = array('success'=>true);
                }*/
                $urlPush = Configure::read('nodeurl')."/getCampaignStatus?".$cid;
                $result = $this->make_request($urlPush,json_encode($message,JSON_NUMERIC_CHECK));
                $this->response->type('json');
                $this->layout = 'ajax';
                $this->set(array(
                    'result' => $result,
                    '_serialize' => array('result')
                ));
                $this->render('/Elements/json');
        }

        public function admin_send(){
                if ($this->request->is('post')) {
                        $sql = $this->request->data['NotificationCampaign']['sql'];
                        if(!empty($sql)){
//                              $users = $this->NotificationCampaign->query($sql);
                                $message = $this->request->data['NotificationCampaign'];
                                if($message['expiresat']['meridian']=='pm'){
                                        $message['expiresat'] = 1000*mktime(($message['expiresat']['hour'])+12,$message['expiresat']['min'],0,$message['expiresat']['month'],$message['expiresat']['day'],$message['expiresat']['year']);
                                }else{
                                        $message['expiresat'] = 1000*mktime($message['expiresat']['hour'],$message['expiresat']['min'],0,$message['expiresat']['month'],$message['expiresat']['day'],$message['expiresat']['year']);                                    
                                }
                                $message['status']='active';
                                $message['smsprocessed']=0;
                                $message['notification_processed']=0;
                                $urlPush = Configure::read('nodeurl')."/addNotificationCampaign";
                                $result = $this->make_request($urlPush,json_encode($message,JSON_NUMERIC_CHECK));
                                if ($result['msg']=='Success'){
//                                      $this->loadModel('Pushnotification');
//                                      $sentUsers = array();
//                                      $payload = array();
//                                      foreach ($users as $key => $value) {    
//                                              if(!in_array($value['User']['id'], $sentUsers)) {
//                                                      $sentUsers[] = $value['User']['id'];                                                            
//                                                      $data = array('notification_campaign_id'=>$message['cid'],'user_id'=>$value['User']['id'],'type'=>'pending','status'=>0);
//                                                      // $this->Pushnotification->create();
//                                                      // $this->Pushnotification->save($data);
//                                                      $payload[] = $data;
//                                              }
//                                      }
//                                      $url = Configure::read('nodeurl')."/addPushNotification";//remove hardcoded value
//                                      $this->make_request($url,json_encode($payload,JSON_NUMERIC_CHECK));
                                        $this->Session->setFlash(__('Push notification scheduled for users'));
                                        return $this->redirect(array('controller' => 'administration', 'action' => 'dashboard', 'admin' => false));
                                }else{
                                        $this->Session->setFlash(__('Notification Campaign Insertion Failed. '));
                                        return $this->redirect(array('controller' => 'administration', 'action' => 'dashboard', 'admin' => false));
                                }                                                                       
                        }
                }
        }
        
        public function admin_user_polling(){
                $page = $this->request->query('page');
                if(!isset($page)){
                        $page = 1;
                }
                $limit = 50;
                $offset = ($page - 1)*$limit;
                $url = Configure::read('nodeurl').'/fetchPollUsers?limit='.$limit.'&offset='.$offset;           
                $response = $this->make_request( $url, null );
                foreach ($response as $key => $value) {                 
                        $response[$key]['updatedOn'] = date('Y-m-d H:i:s', $value["updatedOn"]/1000);
                        $response[$key]['createdOn'] = date('Y-m-d H:i:s', $value["createdOn"]/1000);
                }
                $this->set(compact('response','page'));
        }
}