Sunday, November 18, 2012

Customer migrate from programmacally

we can migrate customer using direct accessing with model class. its so faster than using soap api.(*4 faster)


<?php
date_default_timezone_set(date_default_timezone_get());
$timezone=date_default_timezone_get();
require_once('../config/script_config.php');
require_once('../class/error_log_class.php');
require_once('../class/db_class.php');
require_once('../class/common_functions.php');


 $time_now = date("Y-m-d G:i:s");
 echo '# --start time'.$time_now;

print("\n# Starting Script (customer Create)\n");
print("# Memory Usage : ".round((memory_get_usage()/1048576),2) ."MB \n");

$com_func = new CommonFunctions();
$com_func->setCustomParameters( array("-nor") );
$cmd_args = $com_func->getArgs($argv);

$mage_num_rec   = $cmd_args['-nor'];

$log = new Logger(LOG_PATH.'customer_create_log.txt', LOG_LEVEL);

$setUTF="SET character_set_results =  'utf8',
             character_set_client =  'utf8',
             character_set_connection = 'utf8',
             character_set_database =  'utf8',
             character_set_server =  'utf8';";

$db = new Database();
$db->connect();

try{



$query_max_id="SELECT  IFNULL(MAX(pp_cus_id),0) AS pp_cus_id FROM ".TBL_MIGRATION_CUSTOMER_CREATE."
                where email_duplicate=0;";
$db->queryExecute($query_max_id);
$rows = $db->getResult();


$query_dup_max_id="SELECT  IFNULL(MAX(pp_cus_id),0) AS pp_dup_cus_id FROM ".TBL_MIGRATION_CUSTOMER_CREATE."
               ;";
$db->queryExecute($query_dup_max_id);
$dup_rows = $db->getResult();


$last_cus_id =@$rows[0]['pp_cus_id'];
$last_dup_cus_id =@$dup_rows[0]['pp_dup_cus_id'];


if($last_cus_id==0 && $last_dup_cus_id ==0 ){

echo "Migrating customers with duplicate email addresses \n";
$exquery = " SELECT COUNT( cs.cus_id ) ,
                                    cs.cus_id,
                                    cs.cus_vatnumber,
                                    cs.cus_created,
                                    cs.cus_enabled,
                                    cs.date_of_birth,
                                    cs.cus_f_name,
                                    cs.cus_l_name,
                                    cs.cus_email,
                                    cs.password,
                                    cs.lang_id,
                                    cs.curr_id
                                FROM  (select * from `tbl_customer` ORDER BY cus_id DESC) AS cs
                                WHERE cs.cus_id >0 and cs.`cus_email`<>''
                                GROUP BY cs.`cus_email`
                                HAVING COUNT( cs.`cus_id` ) >1
                                ORDER BY cs.`cus_id` ASC ;";

}else{


$exquery = " SELECT  COUNT( cs.`cus_id` ),
                    cs.cus_id,
                    cs.cus_vatnumber,
                    cs.cus_created,
                    cs.cus_enabled,
                    cs.date_of_birth,
                    cs.cus_f_name,
                    cs.cus_l_name,
                    cs.cus_email,
                    cs.password,
                    cs.lang_id,
                    cs.curr_id
                    FROM  `tbl_customer` cs
                    WHERE cs.cus_id >$last_cus_id
                    AND cs.`cus_email` <>  ''
                    GROUP BY cs.`cus_email`
                    HAVING COUNT( cs.`cus_id` ) =1
                    ORDER BY cs.`cus_id` ASC
                    LIMIT $mage_num_rec ;";

 }


$db->executeNonReturn($setUTF);
$db->queryExecute($exquery);
$res = $db->getResult();
//print_r($res);
$res_count = count($res);

if($res_count==0){
    $log->LogInfo("No Customers For Migrate in given limit $time_now ");
      die("No Customers For Migrate in given limit");

}


print("# $res_count Customers For Migrate \n");
$log->LogInfo("succesefully connect to mysql and found $res_count Customers For Migrate  ");

}  catch (Exception $e){
$log->LogError(" Login Faild for mysql " .$time_now."..\n");
die("Login Faild for mysql....\n");

}


$num =0;

// try {
//
//        // If some stuff requires api authentification,
//        $client = new SoapClient(WSDL_URL);
//        // then get a session token
//        $session = $client->login(API_USER, API_PWD);
//
//
//        print("# Succsefully Connect To SOAP Server And Logged Succsesfully \n");
//         $log->LogInfo("# Succsefully Connect To SOAP Server And Logged Succsesfully $time_now ");
//
//    } catch (Exception $exc) {
//        print("# There Was an Error , When Try to Connect SOAP server \n");
//        $log->LogError(" Login Faild for " . API_USER);
//        die("SOAP Connection Error. Data -" . $time_now."..\n");
//    }

// path to mage.php
ini_set('include_path', ini_get('include_path') .
PATH_SEPARATOR . INCLUDE_PATH .
PATH_SEPARATOR . dirname(__FILE__));

// include mage.php
include INCLUDE_FILE;

Mage::init();
date_default_timezone_set($timezone);

foreach ($res as $value) {
    //for local Dev Tesing
    $num++;
    $result = null;
    $pp_customer_id=$value['cus_id'];

    $date1=$value['cus_created'];

    // define groups
        $sqlGruop="SELECT t.order_id,IFNULL(teo.ex_seller_id,0) as cus_group_id
            FROM tbl_order t
            join tbl_external_order teo
            on t.order_id=teo.order_id
            left join tbl_external_seller tes
            on tes.ex_id=teo.ex_seller_id
            where t.cus_id=$pp_customer_id
            order by t.order_id DESC";
            $db->executeNonReturn($setUTF);
            $db->queryExecute($sqlGruop);
            $groups = $db->getResult();

            @$pp_group_id = $groups[0]['cus_group_id'];

            if(isset ($pp_group_id)){
                $cus_group_id=$pp_group_id;
            }else{
                 $cus_group_id=DIRECT;
            }
    //end of the define groups

   // settype($is_active, "SmallInt");
  $is_active=($value['cus_enabled']==1?0:1);

      if($value['cus_f_name']==''){
        $fname='.';
      }else{
         $fname=$value['cus_f_name'] ;
      }

          if ($value['cus_l_name']==''){
            $lname='-';
          }else{
           $lname=$value['cus_l_name'] ;
          }


   $web_id=$value['curr_id'];
   $st_id=$value['lang_id'];

   $website_id;
   $store_id;

  if(isset ($value['curr_id'])){
      if($web_id==CURR_USD_ID){
          //USD
          $wesite_id=USD_SITE_ID;
          $store_id=ENGLISH_US_STORE_VIEW_ID;
          }
      else if($web_id==CURR_EUR_ID){
          //Euro
          $wesite_id=EUR_SITE_ID;
          if($st_id==LANG_FR){$store_id=FRENCH_STORE_VIEW_ID;}
          else if($st_id==LANG_DE){$store_id=GERMAN_STORE_VIEW_ID;}
          else if($st_id==LANG_ES){$store_id=ESPANOL_STORE_VIEW_ID;}
          else if($st_id==LANG_IT){$store_id=ITALIANO_STORE_VIEW_ID;}
          else if($st_id==LANG_PT){$store_id=PORTUGUES_STORE_VIEW_ID;}

          }
      else if($web_id==CURR_GBP_ID){
          //GBP
          $wesite_id=GBP_SITE_ID;
          $store_id=ENGLISH_UK_STORE_VIEW_ID;
          }
  }else{
      $wesite_id=GBP_SITE_ID;
      $store_id=ENGLISH_UK_STORE_VIEW_ID;
  }
$email= $value['cus_email'];

/// echo "email--$email --";
// //die ();//

    try {

        $customerInfo = array(
                'customer_id'=> $value['cus_id'],
                'created_at' => $date1,
                'taxvat'     => $value['cus_vatnumber'],
                'firstname'  => $fname,
                'lastname'   => $lname,
                'email'      => $email,
                'confirmation' => $is_active,
                'password_hash' => $value['password'],
                'dob' =>  $value['date_of_birth'],
                'website_id'=> $wesite_id,
                'store_id' => $store_id,
                'group_id' => $cus_group_id,
                'created_in' =>'Admin'
              );
              //print_r($customerInfo);
              //die ();
        if($last_cus_id==0 && $last_dup_cus_id ==0){
            $duplicate=1;
            $migrated=1;
            $email=$email;
        }else{
             $duplicate=0;
             $migrated=1;
        }

$customer_email = $email;  // email adress that will pass by the questionaire
$customer_fname =$fname;      // we can set a tempory firstname here
$customer_lname = $lname;       // we can set a tempory lastname here
//$passwordLength = 10;                    // the lenght of autogenerated password

$customer = Mage::getModel('customer/customer');
$customer->setWebsiteId($wesite_id);
$customer->loadByEmail($customer_email);
/*
* Check if the email exist on the system.
* If YES,  it will not create a user account.
*/

if(!$customer->getId()) {

   //setting data such as email, firstname, lastname, and password

  $customer->setEmail($customer_email);
  $customer->setTaxvat($value['cus_vatnumber'])
          ->setCreatedAt($date1)
          ->setDob($value['date_of_birth'])
          ->setGroupId($cus_group_id)
          ->setConfirmation($is_active)
          ->setCreatedIn('Admin')
          ->setStoreId($store_id)
          ->setWebsiteId($wesite_id)
          ->setEntityId($value['cus_id']);
  $customer->setFirstname($customer_fname);
  $customer->setLastname($customer_lname);
  $customer->setPassword( $value['password']);

}

  //the save the data and send the new account email.
  $customer->save();
  $result=$customer->getId();
  //$customer->setConfirmation(null);
  //$customer->save();
  //$customer->sendNewAccountEmail();
  //
  //api funtion calling
     //$result=$client->call($session, 'customer.create',array($customerInfo));
        $log->LogInfo("New Customer Created With pp_cus_id-" .$pp_customer_id."  Magento id-$result and  Sucsesfully Added to Magento DB ");
        //var_dump($result);
           ///--------------------------------map the table(magento and pp)

            $exquery_map = "INSERT INTO ".TBL_MIGRATION_CUSTOMER_CREATE." (
                        `pp_cus_id` ,`mage_id`,email_duplicate,migrated)
                        VALUES (
                        $pp_customer_id, $result,$duplicate,$migrated);";

            $res = $db->executeNonReturn($exquery_map);
   if ( !$res ) throw new Exception("Insert failed to mapping table. SQL: ".$exquery_map);
            $log->LogInfo(" pp_cus_id-" .$pp_customer_id." and Magento id-$result Sucsesfully Added PP Mapping table ");


            if($last_cus_id==0 && $last_dup_cus_id ==0){

            $migrated=0;
            $result=0;
            $duplicate=1;
            $dulicate_email_not_migrated_sql="SELECT cus_id FROM tbl_customer
                                                    where cus_email='".$email."'
                                                    ORDER BY `cus_id` ASC ;";

                $db->queryExecute($dulicate_email_not_migrated_sql);
                $res_dulicate_email_not_migrated_sql = $db->getResult();
                $res_dulicate_email_not_migrated_count = count($res_dulicate_email_not_migrated_sql);

            for($i=0;$i< $res_dulicate_email_not_migrated_count-1;$i++){

                     $pp_customer_not_migrated_id=$res_dulicate_email_not_migrated_sql[$i]['cus_id'];

                     $exquery_map = "INSERT INTO ".TBL_MIGRATION_CUSTOMER_CREATE." (
                                `pp_cus_id` ,`mage_id`,email_duplicate,migrated)
                                VALUES (
                                $pp_customer_not_migrated_id, $result,$duplicate,$migrated);";

                    $res = $db->executeNonReturn($exquery_map);
                    if ( !$res ) throw new Exception("Insert failed to mapping table. SQL: ".$exquery_map);
                    $log->LogInfo(" pp_cus_id-" .$pp_customer_not_migrated_id."-- duplicating Email - not migrated to magento  ");
            }
        }

        ///----------------------------------
       // print("# Customer id $pp_customer -  Migrate Sucsesfully -new Magento Id- $result \n");

    } catch (Exception $exc) {
        print("pp Customer Id ".$pp_customer_id." -  Migrate Fail..!!!!\n");
        $log->LogError(" Error Occerd Customer id " .$pp_customer_id . " Migrate ".$exc);
        die("pp Customer Id ".$pp_customer_id." -  Migrate Fail..!!!!...\n");
        //continue;


    }




}

print("# ---End Of customer Migration Script----\n");
print("# Memory Usage : " . round((memory_get_usage() / 1048576), 2) . "MB \n");
$time_end = date("Y-m-d G:i:s");
print "# --End time'.$time_end.....\n";
?>

No comments:

Post a Comment