Below is the code in the cron I used. Could be useful to someone. I use an abstract file for my common functions, which is not included here.
<?php
// File shell/setStock.php
require_once 'abstract.php';
class Mage_Shell_setStock extends Mage_Shell_Scripts_AbstractMage_Shell_Abstract {
public function run() {
$stockCollection = Mage::getModel('cataloginventory/stock_item')->getCollection()
//->addFieldToFilter('is_in_stock', Mage_CatalogInventory_Model_Stock_Status::STATUS_OUT_OF_STOCK)
->addFieldToFilter('type_id', 'configurable')->load(true);
foreach ($stockCollection as $stockObject) {
$childStockQty = 0;
$product = mage::getModel('catalog/product')->load($stockObject->getProductId());
if ($product->getSku() != '' && $product->getTypeId() == 'configurable') {
$children = $product->getTypeInstance()->getUsedProducts();
if (count($children) > 0) {
foreach ($children as $child) {
$childStock = $child->getStockItem();
$childStockQty += $childStock->getQty();
}
if ($childStockQty > 0 && $product->getIsInStock() == Mage_CatalogInventory_Model_Stock_Status::STATUS_OUT_OF_STOCK) {
echo 'Found configurable that is out of stock, but has stock children : setting in stock. ' . $product->getSku() . "\n";
mage::log('Found configurable that is out of stock, but has stock children : setting in stock. ' . $product->getSku());
if ($this->getArg('dry-run') == false) {
$stockObject->setIsInStock(True);
$stockObject->save();
$this->_doReindexFlag = true;
}
} elseif ($childStockQty == 0 && $product->getIsInStock() == Mage_CatalogInventory_Model_Stock_Status::STATUS_IN_STOCK) {
echo 'Found configurable that is in stock , but has no stock children : setting out of stock. ' . $product->getSku() . "\n";
mage::log('Found configurable that is in stock , but has no stock children : setting out of stock. ' . $product->getSku());
if ($this->getArg('dry-run') == false) {
$stockObject->setIsInStock(False);
$stockObject->save();
$this->_doReindexFlag = true;
}
}
} else {
if ($product->getSku() != '') {
echo 'Found configurable that has no children : setting out of stock. ' . $product->getSku() . "\n";
mage::log('Found configurable that has no children : setting out of stock. ' . $product->getSku());
if ($this->getArg('dry-run') == false) {
$stockObject->setIsInStock(False);
$stockObject->save();
$this->_doReindexFlag = true;
}
}
}
} else {
//
}
}
if ($this->_doReindexFlag) {
mage::log("Re-indexing");
$this->reindex(array('cataloginventory_stock',
'catalogsearch_fulltext',
'catalog_url'));
}
}
}
$shell = new Mage_Shell_setStock();
$shell->run();