0

I am using the code below to filter orders by their status and after to change it to complete

use Psr\Log\LoggerInterface;

class OrderStatus {
    /**
     * @var \Magento\Sales\Api\OrderRepositoryInterface
     */
    protected $_orderRepository;

    /**
     * @var \Magento\Framework\Api\SearchCriteriaBuilder
     */
    protected $_searchCriteriaBuilder;

    /**
     * @var \Magento\Sales\Model\Convert\Order
     */
    protected $_convertOrder;

    /**
     * @var Psr\Log\LoggerInterface
     */
    protected $_logger;

    /**
     * @var Magento\Catalog\Model\Product
     */
    protected $_product;

    /**
     * @var Magento\CatalogInventory\Api\StockStateInterface 
     */
    protected $_stockStateInterface;

    /**
     * @var Magento\CatalogInventory\Api\StockRegistryInterface 
     */
    protected $_stockRegistry;    

    /**
     * @param \Magento\Sales\Api\OrderRepositoryInterface  $orderRepository
     * @param \Magento\Framework\Api\SearchCriteriaBuilder $searchCriteriaBuilder
     * @param \Magento\Sales\Model\Convert\Order           $convertOrder
     * @param Magento\Catalog\Model\Product                $product
     * @param Magento\CatalogInventory\Api\StockStateInterface $stockStateInterface,
     * @param Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
     */

    public function __construct(
        LoggerInterface $_logger,
        \Magento\Sales\Api\OrderRepositoryInterface $_orderRepository,
        \Magento\Framework\Api\SearchCriteriaBuilder $_searchCriteriaBuilder,
        \Magento\Sales\Model\Convert\Order $_convertOrder,
        \Magento\Catalog\Model\Product $_product,
        \Magento\CatalogInventory\Api\StockStateInterface $_stockStateInterface,
        \Magento\CatalogInventory\Api\StockRegistryInterface $_stockRegistry
    )
    {
        $this->logger = $_logger;
        $this->orderRepository = $_orderRepository;
        $this->searchCriteriaBuilder = $_searchCriteriaBuilder;
        $this->_convertOrder = $_convertOrder;
        $this->_product = $_product;
        $this->_stockStateInterface = $_stockStateInterface;
        $this->_stockRegistry = $_stockRegistry;
    }

   /**
    * Write to system.log
    *
    * @return void
    */
    public function execute() {
        $_getOrders = [];
        $_searchCriteria = $this->searchCriteriaBuilder
        ->addFilter(
           'status',
           'pending',
           'eq'
        )->create();

        $_failed_ids = [];
        $_orders = $this->orderRepository->getList($_searchCriteria);

        $this->logger->info('--- ORDERS PENDING --- ');
        foreach ($_orders->getItems() as $_order) {
            //$this->logger->info('Order id : ' . $_order->getId());
            try{
                $_checkcustomer = $_order->getCustomerId();
                // to check order can ship or not
                if (!$_order->canShip()) {
                        $this->logger->info("You can't create the Shipment for order with id : " . $_order->getId() );
               } else {

                        $_completeStatus = \Magento\Sales\Model\Order::STATE_COMPLETE;
                        $_order->setStatus($_completeStatus)->setState($_completeStatus);
                        $this->orderRepository->save($_order); 

                        $this->logger->info('Step 1 - Set order status t complete');

                        foreach ($_order->getAllItems() as $_orderItem) {

                            $_product = $this->_product->load($_orderItem->getProductId()); //load product which you want to update stock
                            $this->logger->info('Step 2 - Product Loaded ');

                            $_currentQty =  $_stockItem->getQty();
                            $this->logger->info('Step 3 - Current quantity : ' . $_currentQty);

                            $_orderedQty = $_orderItem->getQtyToShip();
                            $this->logger->info('Step 4 - Ordered quantity: ' . $_orderedQty);

                            $_remainingQty = $_currentQty - $_orderedQty;
                            $this->logger->info('Step 5 - Remaining quantity: ' . $_remainingQty);

                            $_stock_status = ($_remainingQty > 0) ? 1 : 0;
                            $_product->setStockData(['qty' => $_remainingQty, 'is_in_stock' => 1]);
                            $_product->save(); 
                            $this->logger->info('Step 6 - Product and Quantity saved');

                        }
                    }         
            } catch (NoSuchEntityException $ex) {
                $_failed_ids[] = $_order->getId();
            }
        };

        if (empty($_failed_ids)) {
            $this->logger->info('Orders changes successfully');
        } else {
            $_errormessage = "the following order ids failed : " . implode("," , $_failed_ids);
            $this->logger->info($_errormessage);
        }
    }
}

and it works when the order status is "pending". If I change the filter to "processing" it does not work and that is not normal because I have orders with this status.

Could you please tell me if there is an extra step in order to retrieve these orders?

Thank you very much in advance!

1

Eventually, on my case there was probably an error on the database for orders with status "processing". For that reason, I added an extra filter for "created_at", so that I could get only the results for the last two months, and it worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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