0

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.

1
  • please try my solution as below May 18, 2018 at 11:05

3 Answers 3

1

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

3
  • I tried using your code but still the product qty is not restored.
    – zekia
    May 18, 2018 at 8:15
  • hey have you check configuration, i just edit my answer @zekia
    – Divyesh
    May 18, 2018 at 9:49
  • I need to keep increasing/decreasing stock quantities. This is not a solution for my ehop. As I mentioned in my question, product quantities are restored if I cancel order through magento administration. But it's not working when canceling orders programmatically.
    – zekia
    May 18, 2018 at 10:17
1

Please Try below code for cancel order and manage inventory of Products ordered. Its working fine for me :

ini_set('display_errors',0);
require_once 'app/Mage.php';
Mage::app();
Mage::app()->setCurrentStore(Mage_Core_Model_App::ADMIN_STORE_ID);  
$order = Mage::getModel('sales/order')->loadByIncrementID('100000015'); // Your order increment id
$order->cancel()->save();
9
  • I tested the code and it's not canceling the order. Any ideas?
    – zekia
    May 18, 2018 at 12:25
  • @zekia , code updated. May 18, 2018 at 12:32
  • I'm running this through an .sh file, in case that matters at all
    – zekia
    May 18, 2018 at 13:25
  • Can you try this script for manually in browser? May 18, 2018 at 13:25
  • I'll try this, but my initial script loads and cancels order normally. I think that the $order->cancel()->save(); is not working in your code. I'll let you know in a while
    – zekia
    May 18, 2018 at 13:29
0

Below code worked in Magento 2

Automatically cancel pending payment orders older than 1 day using cron

Create a custom module with required files

Custom/Module/etc/crontab.xml

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Cron:etc/crontab.xsd">
    <group id="default">
        <job name="order_cancel_orders" instance="Custom\Module\Cron\OrderCancelOrders" method="execute">
            <schedule>*/5 * * * *</schedule>
        </job>
    </group>
</config>

Custom/Module/Cron/OrderCancelOrders.php

<?php

namespace Custom\Module\Cron;

use Exception;
use Magento\Framework\Api\SearchCriteriaBuilder;
use Magento\Framework\Exception\NoSuchEntityException;
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Framework\Stdlib\DateTime\DateTime;
use Magento\Sales\Api\OrderManagementInterface;
use Magento\Sales\Api\OrderRepositoryInterface;
use Psr\Log\LoggerInterface;
use Magento\Sales\Model\Order;

class OrderCancelOrders
{

    protected $productRepository;
    protected $dateTime;
    protected $logger;
    protected $date;
    protected $orderRepository;
    protected $searchCriteriaBuilder;
    protected $orderManagement;

    public function __construct(
        ProductRepositoryInterface $productRepository,
        DateTime $dateTime,
        TimezoneInterface $date,
        LoggerInterface $logger,
        OrderRepositoryInterface $orderRepository,
        SearchCriteriaBuilder $searchCriteriaBuilder,
        OrderManagementInterface $orderManagement
    )
    {
        $this->productRepository = $productRepository;
        $this->dateTime = $dateTime;
        $this->logger = $logger;
        $this->date = $date;
        $this->orderRepository = $orderRepository;
        $this->searchCriteriaBuilder = $searchCriteriaBuilder;
        $this->orderManagement = $orderManagement;
    }

    public function execute()
    {
        $this->logger->info('Orders Cancel cron job running');
        $date = (new \DateTime())->modify('-1 day');
        $this->logger->info('Date'.$date);
        $searchCriteria = $this->searchCriteriaBuilder
            ->addFilter(
                'status',
                'pending_payment',
                'eq'
            )->addFilter(
                'created_at',
                $date->format('Y-m-d'),
                'gt'
            )->setPageSize(
                10
            )->create();
        try {
            $ordersData = $this->orderRepository->getList($searchCriteria);
            foreach ($ordersData->getItems() as $orders) {
                if ($orders->getId()) {
                    $this->orderManagement->cancel($orders->getId());
                    $this->logger->info("OrderID# {$orders->getId()} OrderIncrementID# {$orders->getIncrementId()} successfully order canceled and reverted stock.");
                }
            }
        } catch (\Exception $e) {
            $this->logger->critical($e->getMessage());
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.