Monday, January 21, 2019

Generate Access Token and Call the function with access token and send multiple records at single shot and get multiple validation and success responses:

Generate Access Token and Call the function with access token and send multiple records at single shot and get multiple validation and success responses:

In Controller:

<?php
require APPPATH . '/libraries/REST_Controller.php';
class Monthlydata extends REST_Controller {
    public function __construct() {
                parent::__construct();
                date_default_timezone_set('Asia/Kolkata');
                $this->load->model('Monthlydata_model');
    }
    public function generate_access_token_post(){
      $username = $this->post('username');
      $password = $this->post('password');
      $data =array('username'=>$username,'password'=>$password);
      $accesResponse= $this->Monthlydata_model->createAccessToken($data);
      $this->set_response($accesResponse, REST_Controller::HTTP_OK);
    }
    public function monthly_update_post(){
    $lrecord = array();
    $inputdata = array();
    $access_token = $this->post('access_token');
    $user_id = $this->post('user_id');
    $ibb_dealer_code = $this->post('ibb_dealer_code');
  if(!empty($access_token) && !empty($user_id)){
    $checkAccessToken = $this->Monthlydata_model->check_access_token($access_token,$user_id);
    if(is_array($checkAccessToken) && count($checkAccessToken)>0){
    $inputdata = $this->post('inputData');
    $successData= array();
    $err_msgs = array();
      $i=0;
      $row_count = 0;
      $fail_count = 0;
      $abm_fail_count = 0;
      $int_validation_count = 0;     
foreach ($inputdata as $val) {
            $ibb_dealer_code = trim($val['ibb_dealer_code']);
            $do_issued_as_on_date = trim($val['do_issued_as_on_date']);
            if(empty($ibb_dealer_code) || empty($do_issued_as_on_date)){
                   $fail_count++;
              }             
              if (filter_var($do_issued_as_on_date, FILTER_VALIDATE_INT)) {
          $checkIbbDealerCode = $this->Monthlydata_model->ibb_dealer_code_already_exists($ibb_dealer_code);
             if(!empty($ibb_dealer_code) && $checkIbbDealerCode[0]['abm_remarks']!='') {             
              $lrecord['percentage_achievement']=0;
              if($checkIbbDealerCode[0]['target_for_the_curr_month']!=0 && $checkIbbDealerCode[0]['target_for_the_curr_month'] >0){
                    $lrecord['percentage_achievement'] = round(($do_issued_as_on_date/$checkIbbDealerCode[0]['target_for_the_curr_month'])*100);

                   $lrecord['difference_in_units'] = round($do_issued_as_on_date-$checkIbbDealerCode[0]['target_for_the_curr_month']);
              }
              $lrecord['do_issued_as_on_date'] = $do_issued_as_on_date;
              $lrecord['last_modified_on'] = date('Y-m-d H:i:s');
              $lrecord['last_modified_by'] = $val['user_id'];
              $this->Monthlydata_model->update_single_row($checkIbbDealerCode[0]['ibb_dealer_code'],$lrecord);             
              $successData[$i]['message'] = "Updated successfully";
              $successData[$i]['id'] = $checkIbbDealerCode[0]['id'];
              $successData[$i]['ibb_dealer_code'] = $checkIbbDealerCode[0]['ibb_dealer_code'];
              $i++; 
              $row_count++;   
           
            }else{
            $abm_fail_count++;         
            }
        }elseif(!empty($do_issued_as_on_date)){
         $int_validation_count++;

        } // do_issued_as_on_date integer validation end
       
      } // foreach end
      if($fail_count>0){
        array_push($err_msgs,$fail_count." rows are failed to update, IBB dealer code and Do issued as on date fields are mandatory");
      }
      if($abm_fail_count>0){
        array_push($err_msgs,$abm_fail_count." rows are failed to update, ABM does not have entered certain details or IBB dealer code was not found");
      }
      if($int_validation_count>0){
        array_push($err_msgs,$int_validation_count." rows are failed to update, do issued as on date should be an integer");
      }
      $this->set_response(['errors'=>$err_msgs,'success' =>$successData,'status'=>'success','status_code'=>'200'], REST_Controller::HTTP_OK);
     }else{
      $this->set_response(['status'=>'false','message'=>'Access token expired or invalid'], REST_Controller::HTTP_OK);
    }
  }else{
        $this->set_response(['status'=>'false','message'=>'access token or user id cannot be empty'], REST_Controller::HTTP_OK);
  }
}
}


In Model:

<?php
class Monthlydata_model extends CI_Model {
    function check_access_token($access_token,$user_id){
        $this->db->select('id,access_token,expires_at');
          $this->db->from('user_login');
          $this->db->where('access_token',$access_token);
          $this->db->where('expires_at >=',date("Y-m-d H:i:s"));
          //$this->db->where('id',$user_id);
          return $this->db->get()->result_array();
          //echo $this->db->last_query();die;       
    }
    function createAccessToken($data){
          $this->db->select('id,access_token,expires_at');
          $this->db->from('user_login');
          $this->db->where('username',$data['username']);
          $this->db->where('password', md5($data['password']));
          $query = $this->db->get();
          if($query->num_rows() == 1)
          {
           $result = $query->row();
           if($result->expires_at < date("Y-m-d H:i:s")){
            $accessToken = $this->randomKey(39);
            $expire_time = date("Y-m-d H:i:s", strtotime('+24 hours'));
           
            $this->db->where('id',$result->id);
            $this->db->update('user_login',array('access_token'=>$accessToken,'expires_at'=>$expire_time));
            $return = array('status'=>'success','access_token'=>$accessToken,'expires_at'=>$expire_time);   
           } else {
            $return = array('status'=>'success','access_token'=>$result->access_token,'expires_at'=>$result->expires_at);
           }
          } else {
           $return = array('status'=>'failure','message'=>'Invalid username/password.');
          }
        return $return;
    }
     function randomKey($length){
      $pool = array_merge(range(0,9), range('a', 'z'),range('A', 'Z'));
      $key = null;
      for($i=0; $i < $length; $i++) {
        $key .= $pool[mt_rand(0, count($pool) - 1)];
      }
      return $key;
     }
    function ibb_dealer_code_already_exists($ibb_dealer_code){
        $this->db->where('ibb_dealer_code',$ibb_dealer_code);
        $query = $this->db->get('master_data_reports');
        if ($query->num_rows() > 0){
          return $data = $query->result_array();
        }else{
          return false;
        }
    }
    function update_single_row($lead_id,$data) {
        $this->db->where("ibb_dealer_code", $lead_id);
        $this->db->update('master_data_reports', $data);
        return true;
    }

}

?>

Tuesday, January 8, 2019

Post values file handling

 // POST VALUES
  date_default_timezone_set('Asia/Kolkata');
  $path = 'debug_log/debug_log.txt';
  file_put_contents($path, print_r('<<<<< POST VALUES_'.date('Y-m-d H:i:s'),true).' >>>>>', FILE_APPEND);
  $this->content = str_repeat(PHP_EOL, 1);
  $this->content .= print_r($_POST,true);
  $this->content .= str_repeat(PHP_EOL, 1);
  $this->content .= '============================================' . PHP_EOL . PHP_EOL; 
  file_put_contents($path, $this->content, FILE_APPEND); 
 // FILES VALUES
  file_put_contents($path, print_r('<<<<< IMAGES_'.date('Y-m-d H:i:s'),true).' >>>>>', FILE_APPEND);
  $this->content_file = str_repeat(PHP_EOL, 1);
  $this->content_file .= print_r($_FILES,true);
  $this->content_file .= str_repeat(PHP_EOL, 1);
  $this->content_file .= '============================================' . PHP_EOL . PHP_EOL;
  file_put_contents($path, print_r($this->content_file,true), FILE_APPEND);

  echo '<pre>'; print_r($_POST);
  echo '<pre>'; print_r($_FILES);
  exit;

Date wise Ascending or Descending Order (AND) Order by multiple different columns

Current month lead first then previous months leads and then "follow_up_date_time" null leads:

SELECT `lead_id`, `lead_cre_type`, `lead_cre_date`, `lead_status`, `agmt_no`, `cus_name`, `cus_mobile`, `state`, `ms`.`city_name`, `agmt_no`, `veh_reg_no`, `mfcw_id`, `branch`, `branch_code`, `mmv`, `given_for`, `cc_remark`, `remarks`, `reason`, `assigned_on`, `final_agmt_no`, `follow_up_date_time`, `inprgs_datetime`, `lead_date_time`, `application_no` as `emlap_id`, `mf_lead_id` as `crm_id`, `final_agmt_no` as `contract_number`, `contract_date`, `sub_stage`, `appl_no`, `lead_from`
FROM `custom_leads`
LEFT JOIN `master_cities` as `ms` ON `ms`.`city_id` = `custom_leads`.`city_id`
WHERE `assigned_to` = '4900'
AND `lead_status` = '3'
AND (`follow_up_date_time` IS NULL OR  date_format(substr(follow_up_date_time,1,10),'%Y-%m-%d') <= '2019-01-31' OR   month(date_format(substr(follow_up_date_time,1,10),'%Y-%m-%d')) <= month(CURRENT_DATE())) ORDER BY
date_format(substr(follow_up_date_time,1,10),'%Y-%m-%d')  >= CURRENT_DATE() DESC,
date_format(substr(follow_up_date_time,1,10),'%Y-%m-%d')  ASC,
date_format(substr(follow_up_date_time,1,10),'%Y-%m-%d')  < CURRENT_DATE() DESC

Order by multiple different columns(Set of leads one after another with descending order by date):


SELECT
  `ui`.`uid`,
    `ui`.`user_fname` AS `exec_name`,
    `l`.`mf_lead_id`,
    `ul`.`sap_code`,
    `ui`.`user_mobile` AS `exec_mobile`,
    `l`.`lead_id`,
    DATE_FORMAT(SUBSTR(l.lead_cre_date, 1, 10),
            '%d/%m/%Y') AS lead_cre_date,
    `l`.`lead_cre_type`,
    DATE_FORMAT(SUBSTR(l.last_modified_on, 1, 10),
            '%d/%m/%Y') AS last_modified_on,
     l.lead_category,     
    `l`.`lead_status`,
    `l`.`abm_lead_status`,
    `l`.`cus_name`,
    `l`.`cus_mobile`,
    `l`.`veh_reg_no`,
    `l`.`mfcw_id`,
    `l`.`agmt_no`,
    `l`.`final_agmt_no`,
    `l`.`branch`,
    `l`.`branch_id`,
    `l`.`mmv`,
    `l`.`given_for`,
    `l`.`assigned_to`,
    `l`.`cc_remark`,
    `l`.`remarks`,
    DATE_FORMAT(SUBSTR(l.do_date, 1, 10), '%d/%m/%Y') AS do_date,
    `l`.`abm_cnc_remarks`,
    DATE_FORMAT(SUBSTR(l.follow_up_date_time, 1, 10),
            '%d/%m/%Y') AS follow_up_date_time,
    DATE_FORMAT(SUBSTR(l.inprgs_datetime, 1, 10),
            '%d/%m/%Y') AS inprgs_datetime,
    `C`.`city_name`,
    `l`.`lead_for`,
    `l`.`mmfsl_stage`,
    `l`.`mmfsl_code`,
    `l`.`appl_no`,
    `l`.`final_agmt_no`,
    `l`.`veh_fin_amt`,
    `l`.`emlap_user_id`,
    `l`.`emlap_date_time`,
    (CASE
        WHEN l.lead_from = 'referral-app' THEN T.state_name
        ELSE S.state_name
    END) AS state_name,
    `l`.`application_no`,
    DATE_FORMAT(SUBSTR(l.first_contacted_date, 1, 10),
            '%d/%m/%Y') AS first_contacted_date,
    (CASE
        WHEN A.user_type = '1' THEN 'Super Admin'
        WHEN A.user_type = '3' THEN 'Executive'
        WHEN A.user_type = '5' THEN 'ABM'
        WHEN A.user_type = '16' THEN 'Mini User'
    END) AS user_type,
    `A`.`username` AS `lead_created_username`,
    `l`.`lead_type`,
    (CASE
        WHEN l.workable_month = '1' THEN 'Workable This Month'
        WHEN l.workable_month = '2' THEN 'Workable Next Month'
    END) AS workable_month
FROM
`custom_leads` AS `l`
LEFT JOIN
`user_login` AS `ul` ON `ul`.`id` = `l`.`assigned_to`
LEFT JOIN
`user_login` AS `A` ON `A`.`id` = `l`.`lead_cre_user_id`
LEFT JOIN
`user_info` AS `ui` ON `ui`.`uid` = `ul`.`id`
LEFT JOIN
`master_cities` AS `C` ON `C`.`city_id` = `l`.`city_id`
LEFT JOIN
`master_states` AS `S` ON `S`.`state_id` = `l`.`state_id`
LEFT JOIN
`refertowin_master_states` AS `T` ON `T`.`id` = `l`.`state_id`
WHERE
`l`.`lead_status` != '8'
ORDER BY
   (CASE
      WHEN lead_category = 'CLMS' AND lead_cre_type='Bulk' THEN 0
      WHEN lead_category IS NULL AND lead_cre_type='Bulk' THEN 1
       WHEN lead_from = 'referral-app' AND lead_cre_type='Single' THEN 2
       WHEN lead_from IS NULL AND lead_cre_type='Single' THEN 3
       ELSE 4   
    END),
   date(lead_cre_date) desc