4

For some reason order canceled in bulk through my customly added order cancel mass action. Now I need to uncancel all orders.

  • Change status from cancel to the status that was previously set on order
  • Change state of order that was previously set
  • Subtract all quantities of products which are used in the order that are just reverted by cancelling.
  • Remove order history comments

Any help, experience and knowledge sharing would be highly appreciated.

2 Answers 2

4

Create a helper in any of your module

app/code/Vendor/Module/Helper/Data.php

And use following code:

<?php

namespace Vendor\Module\Helper;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper;
use Magento\Sales\Model\Order;
use Magento\CatalogInventory\Model\Indexer\Stock\Processor as StockProcessor;
class Data extends AbstractHelper
{
    /**
     * @var \Magento\CatalogInventory\Api\StockManagementInterface
     */
    protected $stockManagement;
    /**
     * @var StockProcessor
     */
    protected $stockIndexerProcessor;

    public function __construct(
        Helper\Context $context,
        \Magento\CatalogInventory\Api\StockManagementInterface $stockManagement,
        StockProcessor $stockIndexerProcessor
    )
    {
        parent::__construct($context);
    }

    public function uncancleorder($order, $comment = "")
    {
        if(!($order)){
            throw new \Magento\Framework\Exception\LocalizedException(__('Invalid Order'));
        }

        if ($order->isCanceled()) {
            $state = Order::STATE_PROCESSING;
            $productStockQty = [];
            foreach ($order->getAllVisibleItems() as $item) {
                $productStockQty[$item->getProductId()] = $item->getQtyCanceled();
                foreach ($item->getChildrenItems() as $child) {
                    $productStockQty[$child->getProductId()] = $item->getQtyCanceled();
                    $child->setQtyCanceled(0);
                    $child->setTaxCanceled(0);
                    $child->setDiscountTaxCompensationCanceled(0);
                }
                $item->setQtyCanceled(0);
                $item->setTaxCanceled(0);
                $item->setDiscountTaxCompensationCanceled(0);
            }

            $order->setSubtotalCanceled(0);
            $order->setBaseSubtotalCanceled(0);
            $order->setTaxCanceled(0);
            $order->setBaseTaxCanceled(0);
            $order->setShippingCanceled(0);
            $order->setBaseShippingCanceled(0);
            $order->setDiscountCanceled(0);
            $order->setBaseDiscountCanceled(0);
            $order->setTotalCanceled(0);
            $order->setBaseTotalCanceled(0);
            $order->setState($state)
                ->setStatus($order->getConfig()->getStateDefaultStatus($state));
            if (!empty($comment)) {
                $order->addStatusHistoryComment($comment, false);
            }

            /* Reverting inventory */
            $itemsForReindex = $this->stockManagement->registerProductsSale(
                $productStockQty,
                $order->getStore()->getWebsiteId()
            );
            $productIds = [];
            foreach ($itemsForReindex as $item) {
                $item->save();
                $productIds[] = $item->getProductId();
            }
            if (!empty($productIds)) {
                $this->stockIndexerProcessor->reindexList($productIds);
            }
            $order->setInventoryProcessed(true);

            $order->save();

        } else {
            throw new \Magento\Framework\Exception\LocalizedException(__('We cannot un-cancel this order.'));
        }
        return true;
    }
}

Note: Edit this helper according to your requirements.

Now call uncancel method anywhere, just pass order object and comment(if required)

Reference module: https://github.com/Genmato/M2_UnCancelOrder

7
  • 1
    Useful and detailed answer. Commented Apr 25, 2019 at 11:44
  • How to support MSI in Magento 2.3?
    – Nausif
    Commented Sep 17, 2019 at 3:58
  • It misses coupon/store credit/promotions handling. Commented Mar 9, 2021 at 14:22
  • 1
    Worked well for me. Thanks broski
    – ItsJhonny
    Commented Jun 3, 2021 at 8:01
  • Order is reverting back to processing state but the salable quantity is not getting effected. Any one faced this kind of issue in magento 2.4.4 Commented Jul 13, 2022 at 9:24
0

The selected answer doesn't consider MSI. in order to avoid generation a salable qty issue. You could also add this code,

`

public function fixReservationForUncancel(String $incrementId, String $sku, int $qty){

    /** @var \Magento\Framework\ObjectManagerInterface $objectManager */
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();

    /** @var Magento\Framework\App\ResourceConnection $resourceConnection */
    $resourceConnection = $objectManager->create(\Magento\Framework\App\ResourceConnection::class);

    $connection = $resourceConnection->getConnection();
    $tableName = $resourceConnection->getTableName('inventory_reservation');

    $insertQuerry= [
        'stock_id' => 1,//Check your stock id in the same reservation table
        'sku' => $sku,
        'quantity' => $qty*-1,
        'metadata' => '{"event_type":"order_uncancel","object_type":"order","object_id":"","object_increment_id":"'. $incrementId .'"}'
    ];
    
    $qry= $connection->insert($tableName, $insertQuerry);

}

`

Your Answer

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

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