Magento – Cancel order and restore products stock qty

magento-1.9ordersquantitystock

I'm using the following code to cancel programmatically some orders in my magento website:

foreach($orderCollection as $order):
    $order = Mage::getModel('sales/order')->load($order->getId());

    $order->setData('state', "canceled");
    $order->setStatus("canceled");       
    $order->addStatusHistoryComment('Order was automatically canceled');
    $order->save();

    Mage::getModel('jewelsales/order_synch')->cancelOrder($order->getId());
endforeach;

The problem is that the order's product quantities, that were decreased when order was placed, are not increased back their previous state, after order is canceled.

Can you help me fix that?

*Note: Product quantities are restored if I cancel order through magento administration. But it's not working when canceling orders programmatically.

Best Answer

Why you use external cancel functionality to load model each time, Magento Provide cancle() function.

Try This code to cancel order:

if(!$order->canCancel()) {
    throw new Exception('Order cannot be canceled anymore.');
}
$order->cancel();
$order->save();

I give you such idea to use cancel() like:-

$orderModel = Mage::getModel('sales/order');
$orderModel->load($orderId);
if(!$orderModel->canCancel()) {
$orderModel->cancel();
$orderModel->setState(Mage_Sales_Model_Order::STATE_CANCELED, true);
$orderModel->save();
}

System->Configuration-> Catalog ->inventory->stock options->Set Items' Status to be In Stock When Order is Cancelled change this value to "No".

You can also stop to decrease the stock quantity on order placed: System->Configuration-> catalog -> inventory->stock options->Decrease Stock When Order is Placed