4

I am using the following script to update my inventory. After update I want to clean cache, and re-index data, because the updated value on qty is not set in product page. How can I do this?

$mageFilename = '../app/Mage.php';
require_once $mageFilename;
Mage::setIsDeveloperMode(true);
ini_set('display_errors', 1);
umask(0);
Mage::app('admin');
Mage::register('isSecureArea', 1);
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);

set_time_limit(0);
ini_set('memory_limit','1024M');

/***************** UTILITY FUNCTIONS ********************/
function _getConnection($type = 'core_read'){
    return Mage::getSingleton('core/resource')->getConnection($type);
}

function _getTableName($tableName){
    return Mage::getSingleton('core/resource')->getTableName($tableName);
}

function _getAttributeId($attribute_code = 'price'){
    $connection = _getConnection('core_read');
    $sql = "SELECT attribute_id
                FROM " . _getTableName('eav_attribute') . "
            WHERE
                entity_type_id = ?
                AND attribute_code = ?";
    $entity_type_id = _getEntityTypeId();
    return $connection->fetchOne($sql, array($entity_type_id, $attribute_code));
}

function _getEntityTypeId($entity_type_code = 'catalog_product'){
    $connection = _getConnection('core_read');
    $sql        = "SELECT entity_type_id FROM " . _getTableName('eav_entity_type') . " WHERE entity_type_code = ?";
    return $connection->fetchOne($sql, array($entity_type_code));
}

function _checkIfSkuExists($sku){
    $connection = _getConnection('core_read');
    $sql        = "SELECT COUNT(*) AS count_no FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
    $count      = $connection->fetchOne($sql, array($sku));
    if($count > 0){
        return true;
    }else{
        return false;
    }
}

function _getIdFromSku($sku){
    $connection = _getConnection('core_read');
    $sql        = "SELECT entity_id FROM " . _getTableName('catalog_product_entity') . " WHERE sku = ?";
    return $connection->fetchOne($sql, array($sku));
}

function _updateStocks($data){
    $connection     = _getConnection('core_write');
    $sku            = $data[0];
    $newQty         = $data[1];
    $productId      = _getIdFromSku($sku);
    $attributeId    = _getAttributeId();

    $sql            = "UPDATE " . _getTableName('cataloginventory_stock_item') . " csi,
                       " . _getTableName('cataloginventory_stock_status') . " css
                       SET
                       csi.qty = ?,
                       csi.is_in_stock = ?,
                       css.qty = ?,
                       css.stock_status = ?
                       WHERE
                       csi.product_id = ?
                       AND csi.product_id = css.product_id";
    $isInStock      = $newQty > 0 ? 1 : 0;
    $stockStatus    = $newQty > 0 ? 1 : 0;
    $connection->query($sql, array($newQty, $isInStock, $newQty, $stockStatus, $productId));
}
/***************** UTILITY FUNCTIONS ********************/

$csv                = new Varien_File_Csv();
$data               = $csv->getData('stocks.csv'); //path to csv
array_shift($data);

$message = '';
$count   = 1;
foreach($data as $_data){
    if(_checkIfSkuExists($_data[0])){
        try{
            _updateStocks($_data);
            $message .= $count . '> Success:: Qty (' . $_data[1] . ') of Sku (' . $_data[0] . ') has been updated. <br />';

        }catch(Exception $e){
            $message .=  $count .'> Error:: while Upating  Qty (' . $_data[1] . ') of Sku (' . $_data[0] . ') => '.$e->getMessage().'<br />';
        }
    }else{
        $message .=  $count .'> Error:: Product with Sku (' . $_data[0] . ') does\'t exist.<br />';
    }
    $count++;
}
echo $message;

I am trying this, but the update was very slow. I executed this script before echo $message.

$processes = Mage::getSingleton('index/indexer')->getProcessesCollection();
$processes->walk('reindexAll');
$processes->walk('setMode', array(Mage_Index_Model_Process::MODE_REAL_TIME));
$processes->walk('save');
Ankur
  • 2,171
  • 23
  • 29

4 Answers4

3

Create one file in root folder with following code and run it from browser like http://www.domain.com/indexing.php

<?php

// when you get status "Processing" instead of "Ready" in your index management run    this script and it's working fine
 // change the index order as per your requirement currently it's 7 for Catalog Search Index  you can set as per your requirement

 require_once 'app/Mage.php';
 umask( 0 );
 Mage :: app( "default" );

 $indexingProcesses = Mage::getSingleton('index/indexer')->getProcessesCollection(); 
 foreach ($indexingProcesses as $process) {
  $process->reindexEverything();
}

?>

OR put this code in your code

 $indexingProcesses = Mage::getSingleton('index/indexer')->getProcessesCollection(); 
 foreach ($indexingProcesses as $process) {
  $process->reindexEverything();
}

may this will help you!

drsndodiya
  • 1,685
  • 1
  • 17
  • 36
1

Perhaps use cron (help: link 1, link 2, link 3) to run /shell/indexer.php at times you think will be appropriate.

Indexing does take a while. The slow update you experienced is natural. The same thing will happen when you update your index from the backend, it's the same process after all.

As for getting cron working with your setup, I'd suggest that you find some tutorials as it can differ in different environments.

Josh Davenport-Smith
  • 5,456
  • 2
  • 29
  • 40
0

You should try reindexEverything() from Mage_index_Model_Process instead

jacek_podwysocki
  • 807
  • 10
  • 30
0

The Answers given are two valid solutions, here is a 3rd which may become intresting when working with some tenthousand products.

Reindexing can take a log time if you have many products, here are two ways to reduce it:

  1. use magmi importer. First reason: it can do what your script does, you can replace it by magmi. im using it with magento 1.7.0.2. Second reson: it has a On the fly indexer that does update url_rewrites and category_products indexes automatically and even if you update all products, its still faster than a full reindex.

  2. Magento, can reindex individual products, which is faster than a full reindex, especially if you do a incremental import. i do this for the products_price_index

    Mage::app('admin')->setUseSessionInUrl(false);
    Mage::getConfig()->init();
    $product_indexer_price = Mage::getResourceSingleton('catalog/product_indexer_price');
    $product_indexer_price->reindexProductIds(array($this->m_products[$res['products_id']]));
    
bhelm
  • 695
  • 1
  • 7
  • 14