Question

If an order is being canceled, its items should be restored into the inventory. How can this be implemented?

Thanks

Was it helpful?

Solution

I finally found the solution. Just leaving the answer for possible future seekers:

The Magento\Sales\Model\Order has a method named cancel. It would restore Qty, payment, ...

Also there's a cron job in Magento\Sales\Model\CronJob\CleanExpiredOrders which would cancel abandoned orders periodically through its execute method:

public function execute()
{
    $lifetimes = $this->storesConfig->getStoresConfigByPath('sales/orders/delete_pending_after');
    foreach ($lifetimes as $storeId => $lifetime) {
        /** @var $orders \Magento\Sales\Model\ResourceModel\Order\Collection */
        $orders = $this->orderCollectionFactory->create();
        $orders->addFieldToFilter('store_id', $storeId);
        $orders->addFieldToFilter('status', Order::STATE_PENDING_PAYMENT);
        $orders->getSelect()->where(
            new \Zend_Db_Expr('TIME_TO_SEC(TIMEDIFF(CURRENT_TIMESTAMP, `updated_at`)) >= ' . $lifetime * 60)
        );

        try {
            $orders->walk('cancel');
            $orders->walk('save');
        } catch (\Exception $e) {
            $this->logger->error('Error cancelling deprecated orders: ' . $e->getMessage());
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top