Thursday, 26 October 2017

Magento 2 : Create Review & Rating programmatically from other db or csv?

This code is for import reviews from the other database table into magento2 product review.
Step1- Please empty review and rating tables.

Magento 2 Database table list.

  1. review
  2. review_detail
  3. review_entity_summary
  4. review_store
  5. rating_option_vote
  6. rating_option_vote_aggregated


Step2- Create 2 tables in your magento database test_customer and test_reviews.
CREATE TABLE `test_customer` (
  `customerid` int(11) NOT NULL,
  `firstname` varchar(255) NOT NULL,
  `lastname` varchar(255) NOT NULL,
  `emailaddress` varchar(255) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;



CREATE TABLE `test_reviews` (
  `id` int(11) NOT NULL,
  `lastmodified` varchar(255) NOT NULL,
  `productcode` varchar(255) NOT NULL,
  `reviewtitle` varchar(255) NOT NULL,
  `rate` varchar(255) NOT NULL,
  `customerid` varchar(255) NOT NULL,
  `name` varchar(255) NOT NULL,
  `location` varchar(255) NOT NULL,
  `active` varchar(255) NOT NULL,
  `reviewdescription` text NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;



Here you can insert the data from your csv's or other database

Step3- create a php page and paste the below code.

<?php
error_reporting(E_ALL);
set_time_limit(0);
ini_set('display_errors', '1');
ini_set('max_execution_time', 0);
ini_set('memory_limit', '3072M');
ini_set('auto_detect_line_endings', TRUE);

use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();


//Get Customer email for oldsite
function get_customer_email($id)
{
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
    $resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
    $connection = $resource->getConnection();
    $sql = "Select * FROM test_customer_au where customerid=".$id;
    $result = $connection->fetchAll($sql);
   if(count($result)>0){
    $email= $result[0]['emailaddress'];
   }
   else{$email= 'abc@testwebsite.com';}
 
    return $email;
}

// start code where old site review
/*
 * Select * FROM test_reviews where 1
 * I got all the reivew by this query.
 *
 *
 * */

$sql = "Select * FROM test_reviews where 1 ";
$result = $connection->fetchAll($sql);


foreach($result as $kk){
 
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance(); // Instance of object manager
    $customerId = '1234'; // default userid in my case when user is not avalable other wise blank
    $nickname= $kk['name'].', '.$kk['location'];
    $timestamp = '';
    $new_date_format = '';
    $timestamp = strtotime($kk['lastmodified']);
    $new_date_format = date('Y-m-d H:i:s', $timestamp);
 
   // Load product data
    $sku =$kk['productcode'];  
    $productObject = $objectManager->get('Magento\Catalog\Model\Product');
    $product = $productObject->loadByAttribute('sku', $sku);
    $productId = $product->getId();
 
    // Load customer data
    /*
*  I load email id from here by the mapping of ID from the magento2 and custom table using function
* get_customer_email()
*
* */
    if($kk['customerid']!=""){
        $email = get_customer_email($kk['customerid']);
        $customerObj = $objectManager->create('Magento\Customer\Model\ResourceModel\Customer\Collection');
        $collection = $customerObj->addAttributeToSelect('*')
        ->addAttributeToFilter('email',$email)
        ->load();
 
       $cdata=$collection->getData();
       if(isset($cdata[0]['entity_id']) && $cdata[0]['entity_id']!=''){$customerId = $cdata[0]['entity_id'];}else{$customerId = '4611';}
 
    }
 
  // Save Reviews
$bootstrap = Bootstrap::create(BP, $_SERVER);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

     if($kk['active']=="Y"){
$_review = $objectManager->get("Magento\Review\Model\Review")
        ->setEntityPkValue($productId)//product Id
        ->setStatusId(\Magento\Review\Model\Review::STATUS_APPROVED)// approved /PENDING
        ->setTitle($kk['reviewtitle'])
        ->setDetail($kk['reviewdescription'])
        ->setEntityId(1)
        ->setStoreId(2)
        ->setStores(2)
        ->setCustomerId($customerId)//get dynamically here
        ->setNickname($nickname)
        ->save();
    }
    if($kk['active']=="N"){
$_review = $objectManager->get("Magento\Review\Model\Review")
        ->setEntityPkValue($productId)//product Id
        ->setStatusId(\Magento\Review\Model\Review::STATUS_PENDING)// approved /PENDING
        ->setTitle($kk['reviewtitle'])
        ->setDetail($kk['reviewdescription'])
        ->setEntityId(1)
        ->setStoreId(2)
        ->setStores(2)
        ->setCustomerId($customerId)//get dynamically here
        ->setNickname($nickname)
        ->save();
    }
 
   // echo "Review Has been saved ";
 
    /*
    $_ratingOptions = array(
        1 => array(1 => 1,  2 => 2,  3 => 3,  4 => 4,  5 => 5), //quality
        2 => array(1 => 6,  2 => 7,  3 => 8,  4 => 9,  5 => 10),//value
        3 => array(1 => 11, 2 => 12, 3 => 13, 4 => 14, 5 => 15),//price
        4 => array(1 => 16, 2 => 17, 3 => 18, 4 => 19, 5 => 20) //rating
    );
    */
 
    //just Assume user selected rating options
    $ratingOptions ='';
    if($kk['rate'] == "1")
    {
        $ratingOptions = array(
           // '1' => '1',
           // '2' => '7',
           // '3' => '13',
            '4' => '16',
        );
    }
    if($kk['rate'] == "2")
    {
        $ratingOptions = array(
           // '1' => '1',
           // '2' => '7',
           // '3' => '13',
            '4' => '17',
        );
    }
    if($kk['rate'] == "3")
    {
        $ratingOptions = array(
           // '1' => '1',
           // '2' => '7',
           // '3' => '13',
            '4' => '18',
        );
    }
    if($kk['rate'] == "4")
    {
        $ratingOptions = array(
           // '1' => '1',
           // '2' => '7',
           // '3' => '13',
            '4' => '19',
        );
    }
    if($kk['rate'] == "5")
    {
        $ratingOptions = array(
           // '1' => '1',
           // '2' => '7',
           // '3' => '13',
            '4' => '20',
        );
    }
 
    foreach ($ratingOptions as $ratingId => $optionIds) {
        $objectManager->get("Magento\Review\Model\Rating")
            ->setRatingId($ratingId)
            ->setReviewId($_review->getId())
            ->addOptionVote($optionIds, $productId);
    }
 
    // generates summary
            $_review->aggregate();
            // if you want to save review in previous dates
            $_review->setCreatedAt($new_date_format);
            $_review->save();
         

echo "<br/>Rating has been saved success !!!!!!!!!= ".$_review->getId();

}


?>





Wednesday, 18 October 2017

Magento 2 : issues with M2E Pro 'Duplicated line on invoice/order for configurable product'[solved]

Duplicated line on invoice/order for configurable product

When configurable product is ordered, Magento show 2 lines in order (and in invoice)
configurable product generates 2 lines : one with the actual price and the other one with $0 price.

Go this location:
app/code/Ess/M2ePro/Plugin/Order/Magento/Quote/Model/Quote/Item/

Replace 2 function :

public function aroundConvert($interceptor, \Closure $callback, $item)
    {
        return $this->execute('convert', $interceptor, $callback, [$item]);
    }

    // ---------------------------------------

    protected function processConvert($interceptor, \Closure $callback, $arguments)
    {
        $orderItem = $callback($arguments[0]);

        $this->eventManager->dispatch(
            'ess_sales_convert_quote_item_to_order_item',
            [
                'order_item' => $orderItem,
                'item' => $arguments[0],
            ]
        );

        return $orderItem;
    }
 

    To:
 
 
   public function aroundConvert($interceptor, \Closure $callback, ...$arguments)
    {
        return $this->execute('convert', $interceptor, $callback, $arguments);
    }

    // ---------------------------------------

    protected function processConvert($interceptor, \Closure $callback, $arguments)
    {
        $orderItem = $callback(...$arguments);

        $this->eventManager->dispatch(
            'ess_sales_convert_quote_item_to_order_item',
            [
                'order_item' => $orderItem,
                'item' => $arguments[0],
            ]
        );

        return $orderItem;
    }
    

Thursday, 20 July 2017

Kuldeep Singh Dagar: [SOLVED] Magento ver. 1.9.*.* Cant view product im...

Kuldeep Singh Dagar: [SOLVED] Magento ver. 1.9.*.* Cant view product im...: Problem Reasons: Wrong permissions set to uploaded files Solution: Open /lib/Varien/File/Uploader.php and make sure following permission...

[SOLVED] Magento ver. 1.9.*.* Cant view product images in admin after upload

Problem Reasons:

  • Wrong permissions set to uploaded files Solution: Open /lib/Varien/File/Uploader.php and make sure following permissions are set at chmod($destinationFile, 0640);. This code will be at around line 219.



  • Replace: line no 219 -  chmod($destinationFile, 0640); to chmod($destinationFile, 0644); or as per requirement.



  • Then rename .htaccess file to .htaccess.old in /media folder.


I tried the solution and it work fine. 

Please feel free to contact me any Magento issue at any time. 

Regards
Kuldeep
kuldeep4110@gmail.com

Sunday, 2 July 2017

Magento [SOLVED]Can not login to admin panel and website footer error 'Access to undeclared static property'

Fatal error: Access to undeclared static property: Mage::$_isDeveloperMode in app/Mage.php on line 881

Go to Mage.php line number 881 find the function.

public static function getIsDeveloperMode()
{
    return self::$_isDeveloperMode;
}

This method simply returns a static property $_isDeveloperMode of the class app\Mage.php. You can find that the definition of that static property
 in that file itself in line 117 (magento 1.9.1) like this.

Add below code of the class app\Mage.php "static private $_isDeveloperMode = false;"

Find: static private $_isDownloader = false;

    /**
     * Is developer mode flag
     *
     * @var bool
     */
ADD: static private $_isDeveloperMode = false;

I tried the solution and it work fine.

Please feel free to contact me any Magento issue at any time.

Regards
Kuldeep
kuldeep4110@gmail.com

Tuesday, 13 June 2017

How to set up x amount discount in % on all products in magento store

Please folow the below steps.
How to set up x amount discount in % on all products in magento store

  •         Login in admin section
  •         Go to Promotions >> Catalog Price Rules
  •         Then Click Add New Rule
  •         Rule Name: x% discount
  •         Status: Active
  •         Websites : Choose the websites you want to apply the discount for
  •         Customer Groups: Choose the customer groups you want to apply the discount for
  •         In the Actions tab, under Discount Amount type x amount
  •         select apply to the "By Percentage of product original price"
  •         Click Save and Apply


Make sure Action Tab "Enable Discount to Subproducts:Yes"


I tried the solution and it work fine.

Please feel free to contact me any Magento issue at any time.

Regards
Kuldeep
kuldeep4110@gmail.com

Thursday, 8 June 2017

Magento Version 1.6- can't upload product images through admin section.


I Uploaded the product image in admin section with the help of Browse and upload button got error  when we reached on 100% ,it automatic disappear and images is not uploaded.
 The images are being uploaded into the / media / tmp folder, but not into / media / catalog.


 Solution: Please check the below mentioned my solution
 1.  Removing htaccess file from media folder 
 2. Giving 777 permission recursively to Media folder 
 3. Using different browsers
 4.  Replacing both prototype.js and product.js
\js\prototype\prototype.js
\js\mage\adminhtml\product.js

I tried the solution and it work fine. 

Please feel free to contact me any Magento issue at any time. 

Regards
Kuldeep
kuldeep4110@gmail.com