Subversion Repositories SmartDukaan

Rev

Rev 15403 | Blame | Compare with Previous | Last modification | View Log | RSS feed

<?php
App::uses('AppController', 'Controller');
/**
 * Orders Controller
 *
 * @property Order $Order
 * @property PaginatorComponent $Paginator
 */
class OrdersController extends AppController {

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

        public function beforeFilter() {                
                parent::beforeFilter();
                $this->Auth->allow('add','mine','pendingcashbacks','all');
                $this->apihost = Configure::read('pythonapihost');
        }
        
        public function mine() {
                $page = $this->request->query('page');
                $page = isset($page)?$page:1;
                $userId = $this->request->query('user_id');
                if(isset($userId) && !empty($userId)){
                        $this->loadModel('User');
                        $dbuser = $this->User->findById($userId);
                        $this->Auth->login($dbuser['User']);    
                }
                $this->layout = "innerpages";
                $url = $this->apihost."storeorder/user/".$this->Auth->User('id')."?page=$page&window=10";
                $response = $this->make_request($url,null);
                $totalPages = $response['totalPages'];
                if(!empty($response['data'])){
                        $this->set('orders',$response['data']);
                }
                $ignoredFields = array('imgUrl','status','productTitle','estimatedDeliveryDate','productCode','merchantSubOrderId','productUrl','closed','tracingkUrl','detailedStatus');
                $storemapping = Configure::read('storemapping');
                $activestores = Configure::read('activestores');
                $amazonorderurl = Configure::read('amazonorderurl');
                $this->set(compact('ignoredFields','page','totalPages','userId','activestores','storemapping','amazonorderurl'));
        }

        public function pendingcashbacks() {
                $userId = $this->request->query('user_id');
                if(isset($userId) && !empty($userId)){
                        $this->loadModel('User');
                        $dbuser = $this->User->findById($userId);
                        $this->Auth->login($dbuser['User']);    
                }
                $this->layout = "innerpages";
                $url = $this->apihost."storeorder/user/".$this->Auth->User('id')."?page=1&window=50";
                $response = $this->make_request($url,null);
                // debug($response);
                $creditedOrders = $pendingOrders = $approvedOrders = array();
                $creditedAmount = $pendingAmount = $approvedAmount = 0;
                if(!empty($response['data'])){
                        foreach ($response['data'] as $key => $order) {
                                if(!empty($order['subOrders'])){
                                        foreach ($order['subOrders'] as $key => $suborder) {
                                                $suborder['storeId'] = $order['storeId'];
                                                if($order['storeId']!=4){
                                                        $suborder['merchantOrderId'] = $order['merchantOrderId'];
                                                } else {
                                                        $suborder['merchantOrderId'] = $suborder['merchantSubOrderId'];
                                                }
                                                if(!empty($order['orderTrackingUrl'])){
                                                        $suborder['orderSuccessUrl'] = $order['orderTrackingUrl'];
                                                }
                                                switch($suborder['cashBackStatus']){
                                                        // case 'Credited to wallet'://Credited
                                                        // $creditedOrders[] = $suborder;
                                                        // break;
                                                        case 'Approved':
                                                        $approvedOrders[] = $suborder;
                                                        $approvedAmount += $suborder['cashBackAmount'];
                                                        break;
                                                        case 'Pending':
                                                        $pendingOrders[] = $suborder;
                                                        // $pendingAmount += $suborder['cashBackAmount'];
                                                }
                                        }
                                }
                        }
                }
                $url = $this->apihost.'pending-cashbacks/user/'.$userId;
                $result = $this->make_request($url,null);
                $pendingAmount = $result['amount'];
                //Get pending cashbacks
                $url = $this->apihost.'pending-refunds/user/'.$userId;
                $pendingCashbacks = $this->make_request($url,null);
                //Get credited cashbacks
                $url = $this->apihost.'refund/user/'.$userId;
                $creditedCashbacks = $this->make_request($url,null);

                if(!empty($creditedCashbacks)){
                        foreach ($creditedCashbacks['data'] as $key => $value) {
                                $creditedAmount += $value['userAmount'];                                
                                $data = array('subOrders.batchId'=>$value['batch']);
                                $jsonVar = json_encode($data);
                                $url = $this->apihost."storeorder/user/".$this->Auth->User('id')."?page=1&window=50&searchMap=$jsonVar";
                                $creditedOrders[$value['batch']] = $this->make_request($url,null);
                                // debug($creditedOrders);
                        }
                }
                $storemapping = Configure::read('storemapping');
                $activestores = Configure::read('activestores');
                if(!empty($response['data'])){
                        $this->set(compact('storemapping','activestores','pendingOrders','approvedOrders','creditedOrders','pendingCashbacks','creditedCashbacks','pendingAmount','approvedAmount','creditedAmount'));
                }
        }


        public function usercashbacks($userId) {        
                $this->set('byUser',$userId);
                $this->layout = "innerpages";
                $url = $this->apihost."storeorder/user/".$userId."?page=1&window=50";
                $response = $this->make_request($url,null);
                // debug($response);
                $creditedOrders = $pendingOrders = $approvedOrders = array();
                $creditedAmount = $pendingAmount = $approvedAmount = 0;
                if(!empty($response['data'])){
                        foreach ($response['data'] as $key => $order) {
                                if(!empty($order['subOrders'])){
                                        foreach ($order['subOrders'] as $key => $suborder) {
                                                $suborder['storeId'] = $order['storeId'];
                                                if($order['storeId']!=4){
                                                        $suborder['merchantOrderId'] = $order['merchantOrderId'];
                                                } else {
                                                        $suborder['merchantOrderId'] = $suborder['merchantSubOrderId'];
                                                }
                                                if(!empty($order['orderTrackingUrl'])){
                                                        $suborder['orderSuccessUrl'] = $order['orderTrackingUrl'];
                                                }
                                                switch($suborder['cashBackStatus']){
                                                        // case 'Credited to wallet'://Credited
                                                        // $creditedOrders[] = $suborder;
                                                        // break;
                                                        case 'Approved':
                                                        $approvedOrders[] = $suborder;
                                                        $approvedAmount += $suborder['cashBackAmount'];
                                                        break;
                                                        case 'Pending':
                                                        $pendingOrders[] = $suborder;
                                                        // $pendingAmount += $suborder['cashBackAmount'];
                                                }
                                        }
                                }
                        }
                }
                $url = $this->apihost.'pending-cashbacks/user/'.$userId;
                $result = $this->make_request($url,null);
                $pendingAmount = $result['amount'];
                //Get pending cashbacks
                $url = $this->apihost.'pending-refunds/user/'.$userId;
                $pendingCashbacks = $this->make_request($url,null);
                //Get credited cashbacks
                $url = $this->apihost.'refund/user/'.$userId;
                $creditedCashbacks = $this->make_request($url,null);

                $creditKeyArray = array();
                $creditValueArray = array();
                $total_credited_amount = 0;
                if(!empty($creditedCashbacks)){
                        foreach ($creditedCashbacks['data'] as $key => $value) {
                                $creditedAmount += $value['userAmount'];                                
                                $data = array('subOrders.batchId'=>$value['batch']);
                                $jsonVar = json_encode($data);
                                
                                $url = $this->apihost."storeorder/user/".$userId."?page=1&window=50&searchMap=$jsonVar";
                                $creditedOrders[$value['batch']] = $this->make_request($url,null);
                                $total_credited_amount =$total_credited_amount + $value['userAmount'];
                                if($value['type']== 'Order')
                                {
                                        $creditValueArray['amount'] = $value['userAmount'];
                                        $creditValueArray['type'] = $value['type'];
                                        $creditValueArray['fortbatchid'] = $value['batch'];
                                        $creditValueArray['creditedDate'] = date('Y-m-d',strtotime($value['timestamp']));
                                        // $creditKeyArray[date('Y-m-d',strtotime($value['timestamp']))] = $creditValueArray;
                                        $creditKeyArray[date('Y-m-d',strtotime($value['timestamp'])).$value['type']] = $creditValueArray;
                                }
                                
                        }
                }

                $storemapping = Configure::read('storemapping');
                $activestores = Configure::read('activestores');

        // App Credit Start
                $creditedFortnight = array();
                $url = $this->apihost.'appUserCashBack/'.$userId.'/Credited';
                $getcredited = $this->make_request($url,null);
                // debug($getcredited);
                foreach ($getcredited['UserAppCashBack'] as $key => $value) {



                        $url = $this->apihost.'appUserBatchDrillDown/'.$userId.'/'.$value['fortnightOfYear'].'/'.$value['yearVal'];
                        $creditedFortnight[$value['fortnightOfYear']] = $this->make_request($url,null);

                        $creditValueArray['amount'] = $value['amount'];
                        // $total_credited_amount = $total_credited_amount + $value['amount'];
                        $creditValueArray['type'] = 'App';
                        $creditValueArray['fortbatchid'] = $value['fortnightOfYear'];
                        $creditValueArray['creditedDate'] = $value['creditedDate'];
                        $creditKeyArray[$value['creditedDate'].'App'] = $creditValueArray;
                        // echo "total credit",$total_credited_amount;
                        // echo $url;
                }
                
                ksort($creditKeyArray);
                // debug($creditKeyArray);
                $this->set(compact('getcredited','creditedFortnight','creditKeyArray','total_credited_amount'));
                // debug($creditedFortnight);
        // App Credit End

                // Approved Start

                $url = $this->apihost.'appUserCashBack/'.$userId.'/Approved';
                $getapproved = $this->make_request($url,null);
                $fortnight = array();
                $fortnight_amount = array();
                $counter = 0;
                $total_approved_amount = 0;
                $current_date =  date("Y");
                foreach ($getapproved["UserAppCashBack"] as $key => $value) {
                         $fortnight[$counter] = $value["fortnightOfYear"];
                         $fortnight_amount[$counter] = $value["amount"];
                         $total_approved_amount += $value["amount"];
                         $counter++;
                }
                $approvedFortnight = array();
                for($i=0; $i<count($fortnight); $i++){
                        $url = $this->apihost.'appUserBatchDrillDown/'.$userId.'/'.$fortnight[$i].'/'.$current_date;
                        $approvedFortnight[$i] = $this->make_request($url,null);
                
                }
                // debug($approvedFortnight);
                $this->set(compact('fortnight','total_approved_amount','fortnight_amount','approvedFortnight'));                
        // Approved End 

                if(!empty($response['data'])){
                        $this->set(compact('storemapping','activestores','pendingOrders','approvedOrders','creditedOrders','pendingCashbacks','creditedCashbacks','pendingAmount','approvedAmount','creditedAmount'));
                }
        }


        public function by($userId) {
                $page = $this->request->query('page');
                $page = isset($page)?$page:1;           
                $this->layout = "innerpages";
                $url = $this->apihost."storeorder/user/".$userId."?page=$page&window=10";
                $response = $this->make_request($url,null);
                $totalPages = $response['totalPages'];
                if(!empty($response['data'])){
                        $this->set('orders',$response['data']);
                }
                $ignoredFields = array('imgUrl','status','productTitle','estimatedDeliveryDate','productCode','merchantSubOrderId','productUrl','closed','tracingkUrl','detailedStatus');
                $storemapping = Configure::read('storemapping');
                $activestores = Configure::read('activestores');
                $amazonorderurl = Configure::read('amazonorderurl');
                $this->set(compact('ignoredFields','page','totalPages','userId','activestores','storemapping','amazonorderurl'));
        }

/**
 * index method
 *
 * @return void
 */
        public function index() {
                throw new NotFoundException(__('Access Denied'));
                $this->Order->recursive = 0;
                $this->set('orders', $this->Paginator->paginate());
        }

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function view($id = null) {
                throw new NotFoundException(__('Access Denied'));
                if (!$this->Order->exists($id)) {
                        throw new NotFoundException(__('Invalid order'));
                }
                $options = array('conditions' => array('Order.' . $this->Order->primaryKey => $id));
                $this->set('order', $this->Order->find('first', $options));
        }

/**
 * add method
 *
 * @return void
 */

        public function postOrders($order=null) {
                // Configure::load('live');
                $apihost = Configure::read('pythonapihost');
                $url = $apihost."storeorder";
                if(!empty($order)) {
                        $params = array('sourceId'=>$order['Order']['store_id'],'orderId'=>$order['Order']['id'],'subTagId'=>$order['Order']['sub_tag'],'userId'=>$order['Order']['user_id'],'rawHtml'=>$order['Order']['rawhtml'],'orderSuccessUrl'=>$order['Order']['order_url']);
                        $jsonVar = json_encode($params);
                        return $this->make_request($url,$jsonVar);
                }else{
                        $result = array('success'=>false,'message'=>'Empty order array');
                        return $result;
                }
        }

        public function add() {
                $this->log(print_r($this->request->data,1),'orders');
                if ($this->request->is('post')) {
                        if($this->request->data['zip']){
                                $this->request->data['rawhtml'] = gzuncompress(base64_decode($this->request->data['rawhtml'])); 
                        }
                        $this->log(print_r($this->request->data,1),'orders');
                        if(empty($this->request->data['id'])) {
                                $this->Order->create();
                        }
                        $this->request->data['ip'] = $_SERVER['HTTP_CF_CONNECTING_IP'];
                        if ($this->Order->save($this->request->data)) {
                                //$this->loadModel('PythonApi');        
                                if(empty($this->request->data['id'])) {
                                        $id = $this->Order->getLastInsertID();
                                }else{
                                        $id = $this->request->data['id'];
                                }
                                $order = $this->Order->find('first',array('conditions'=>array('id'=>$id),'recursive'=>-1));
                                $response = $this->postOrders($order);
                                $this->log(print_r($response,1),'orders');
                                if(!empty($response) && $response['result']) {
                                        //if($response['result'] == 'HTML_REQUIRED' || $response['result'] == 'requireHtml') {
                                        if($response['htmlRequired'] == 1) {
                                                $this->loadModel('Rawhtml');
                                                $data = array('order_id' => $order['Order']['id'],'url' => $response['url'], 'status' => 'new');
                                                $this->Rawhtml->create();
                                                $this->Rawhtml->save($data); 
                                                //$result =array('success'=>true,'message'=>__('requireHtml'),'url' => $response['url'],'orderId' => $response['orderId']);
                                                $result =  $response;
                                                $sql = "UPDATE orders SET status = '".$response['result']."' WHERE id = ".$order['Order']['id'];
                                        }/* elseif($response['result'] == 'IGNORED') {
                                                $result =array('success'=>true,'message'=>__('IGNORED'));
                                                $sql = "UPDATE orders SET status = 'deleted' WHERE id = ".$order['Order']['id'];
                                        } elseif($response['result'] == 'PARSE_ERROR') {
                                                $result =array('success'=>true,'message'=>__('PARSE_ERROR'));
                                                $sql = "UPDATE orders SET status = 'deleted' WHERE id = ".$order['Order']['id'];
                                        } */
                                        else {
                                                $result =array('success'=>true,'message'=> $response['result']);
                                                $sql = "UPDATE orders SET status = '".$response['result']."' WHERE id = ".$order['Order']['id'];
                                        }
                                        $this->Order->query($sql);
                                }
                                //$result = array('success'=>true,'message'=>__('HTML_REQUIRED'),'url'=>'https://www.amazon.in/gp/css/summary/edit.html?orderID=404-7369214-6566739');
/*
                                $options = array('conditions'=>array('status'=>'mapped'),'recursive'=>-1);
                                $order = $this->Order->find('first',$options);
                                if(!empty($orders)) {
                                        foreach($orders AS $order) {
                                                $response = $this->PythonApi->postOrders($order);
                                                if(!empty($response) && $response['result']) {
                                                        $sql = "UPDATE orders SET status = 'processed' WHERE id = ".$order['Order']['id'];
                                                        $this->Order->query($sql);
                                                }
                                        }
                                }
*/
                        } else {
                                $this->log(print_r($this->Order->validationErrors,1),'orders');
                                $result = array('success'=>false,'message'=>__('The order could not be saved. Please, try again.'));
                        }
                        $this->response->type('json');
                        $this->layout = 'ajax';
                        $this->set(array(
                            'result' => $response,
                            // 'callback' => $callback,
                            '_serialize' => array('result')
                        ));
                        $this->render('/Elements/json');                
                }                       
        }

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function edit($id = null) {
                throw new NotFoundException(__('Access Denied'));
                if (!$this->Order->exists($id)) {
                        throw new NotFoundException(__('Invalid order'));
                }
                if ($this->request->is(array('post', 'put'))) {
                        if ($this->Order->save($this->request->data)) {
                                $this->Session->setFlash(__('The order has been saved.'));
                                return $this->redirect(array('action' => 'index'));
                        } else {
                                $this->Session->setFlash(__('The order could not be saved. Please, try again.'));
                        }
                } else {
                        $options = array('conditions' => array('Order.' . $this->Order->primaryKey => $id));
                        $this->request->data = $this->Order->find('first', $options);
                }
                $users = $this->Order->User->find('list');
                $stores = $this->Order->Store->find('list');
                $storeOrders = $this->Order->StoreOrder->find('list');
                $this->set(compact('users', 'stores', 'storeOrders'));
        }

/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function delete($id = null) {
                throw new NotFoundException(__('Access Denied'));
                $this->Order->id = $id;
                if (!$this->Order->exists()) {
                        throw new NotFoundException(__('Invalid order'));
                }
                $this->request->onlyAllow('post', 'delete');
                if ($this->Order->delete()) {
                        $this->Session->setFlash(__('The order has been deleted.'));
                } else {
                        $this->Session->setFlash(__('The order could not be deleted. Please, try again.'));
                }
                return $this->redirect(array('action' => 'index'));
        }

/**
 * admin_index method
 *
 * @return void
 */
        public function admin_index() {
                $this->Order->recursive = 0;
                $this->set('orders', $this->Paginator->paginate());
        }

/**
 * admin_view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function admin_view($id = null) {
                if (!$this->Order->exists($id)) {
                        throw new NotFoundException(__('Invalid order'));
                }
                $options = array('conditions' => array('Order.' . $this->Order->primaryKey => $id));
                $this->set('order', $this->Order->find('first', $options));
        }

/**
 * admin_add method
 *
 * @return void
 */
        public function admin_add() {
                if ($this->request->is('post')) {
                        $this->Order->create();
                        if ($this->Order->save($this->request->data)) {
                                $this->Session->setFlash(__('The order has been saved.'));
                                return $this->redirect(array('action' => 'index'));
                        } else {
                                $this->Session->setFlash(__('The order could not be saved. Please, try again.'));
                        }
                }
                $users = $this->Order->User->find('list');
                $stores = $this->Order->Store->find('list');
                $storeOrders = $this->Order->StoreOrder->find('list');
                $this->set(compact('users', 'stores', 'storeOrders'));
        }

/**
 * admin_edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function admin_edit($id = null) {
                if (!$this->Order->exists($id)) {
                        throw new NotFoundException(__('Invalid order'));
                }
                if ($this->request->is(array('post', 'put'))) {
                        if ($this->Order->save($this->request->data)) {
                                $this->Session->setFlash(__('The order has been saved.'));
                                return $this->redirect(array('action' => 'index'));
                        } else {
                                $this->Session->setFlash(__('The order could not be saved. Please, try again.'));
                        }
                } else {
                        $options = array('conditions' => array('Order.' . $this->Order->primaryKey => $id));
                        $this->request->data = $this->Order->find('first', $options);
                }
                $users = $this->Order->User->find('list');
                $stores = $this->Order->Store->find('list');
                $storeOrders = $this->Order->StoreOrder->find('list');
                $this->set(compact('users', 'stores', 'storeOrders'));
        }

/**
 * admin_delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
        public function admin_delete($id = null) {
                $this->Order->id = $id;
                if (!$this->Order->exists()) {
                        throw new NotFoundException(__('Invalid order'));
                }
                $this->request->onlyAllow('post', 'delete');
                if ($this->Order->delete()) {
                        $this->Session->setFlash(__('The order has been deleted.'));
                } else {
                        $this->Session->setFlash(__('The order could not be deleted. Please, try again.'));
                }
                return $this->redirect(array('action' => 'index'));
        }

        public function all() {
                $page = $this->request->query('page');
                $page = isset($page)?$page:1;
                // $userId = $this->request->query('user_id');
                // if(isset($userId) && !empty($userId)){
                //      $this->loadModel('User');
                //      $dbuser = $this->User->findById($userId);
                //      $this->Auth->login($dbuser['User']);    
                // }
                $this->layout = "innerpages";
                $url = $this->apihost."orders/?page=$page&window=10";
                $response = $this->make_request($url,null);
                $totalPages = $response['totalPages'];          
                if(!empty($response['data'])){
                        $this->set('orders',$response['data']);
                }
                $ignoredFields = array('imgUrl','status','productTitle','estimatedDeliveryDate','productCode','merchantSubOrderId','productUrl','closed','tracingkUrl','detailedStatus');
                $storemapping = Configure::read('storemapping');
                $activestores = Configure::read('activestores');
                $amazonorderurl = Configure::read('amazonorderurl');
                $allusers = $this->Order->User->find('all',array('fields'=>array('first_name','id'),'recursive'=>-1));
                foreach($allusers AS $user){
                        $users[$user['User']['id']] = $user['User']['first_name'];
                }
                $this->set(compact('ignoredFields','page','totalPages','userId','activestores','storemapping','amazonorderurl','users'));
        }
}