Skip to content

Magento2 Order status not getting updated

Magento2 I need to create Invoice & Shipping pro-grammatically. For that I used following link

https://webkul.com/blog/how-to-programmatically-create-invoice-in-magento2/

Using this code I am able to create invoice as per need but the order status is not getting updated as per need when more then 1 order Id’s are passed in foreach loop. Only the last order Id’s status is getting completed. Rest all order Id’s invoice are getting created by status stays as pending

public function execute()
    {

        $api_response_array = [22,23];

        
        //load by order 

        // Load Order details based on order Id, if order is in pending state create invoice & then shipment else directly shipment

        $responseOrderId = '';

        foreach ($api_response_array as $value) {
            $responseOrderId = $value;
        
        
        //$responseOrderId = 5;

        $collection = $this->_orderCollectionFactory->create()
         ->addAttributeToSelect('entity_id')
         ->addAttributeToSelect('status')
         ->addFieldToFilter('entity_id',$responseOrderId);

         $status = '';

        $logger->info(print_r($collection->getData(), true));
         foreach ($collection->getData() as $value) {
            $status = $value['status'];
         }

         if ((!empty($status)) && ($status == 'pending')) {
            // Pending > First Invoice & then Shipment

            $this->createInvoice($responseOrderId);

            $this->createShipment($responseOrderId);

         }elseif ($status == 'processing') {
            // Processing direct shipment

            $this->createShipment($responseOrderId);

         }

        }
}

    public function createShipment($orderId)
    {
            // Code start to create shipment
            $order = $this->_objectManager->create('MagentoSalesModelOrder')
            ->load($orderId);

            // Check if order can be shipped or has already shipped
            if (! $order->canShip()) {
                throw new MagentoFrameworkExceptionLocalizedException(
                                __('You can't create an shipment.')
                            );
            }

            // Initialize the order shipment object
            $convertOrder = $this->_objectManager->create('MagentoSalesModelConvertOrder');
            $shipment = $convertOrder->toShipment($order);

            // Loop through order items
            foreach ($order->getAllItems() AS $orderItem) {
                // Check if order item has qty to ship or is virtual
                if (! $orderItem->getQtyToShip() || $orderItem->getIsVirtual()) {
                    continue;
                }

                $qtyShipped = $orderItem->getQtyToShip();

                // Create shipment item with qty
                $shipmentItem = $convertOrder->itemToShipmentItem($orderItem)->setQty($qtyShipped);

                // Add shipment item to shipment
                $shipment->addItem($shipmentItem);
            }

            // Register shipment
            $shipment->register();

            $shipment->getOrder()->setIsInProcess(true);

            try {
                // Save created shipment and order
                $shipment->save();
                $shipment->getOrder()->save();

                // Send email
                $this->_objectManager->create('MagentoShippingModelShipmentNotifier')
                    ->notify($shipment);

                $shipment->save();
            } catch (Exception $e) {
                throw new MagentoFrameworkExceptionLocalizedException(
                                __($e->getMessage())
                            );
            }

            // Code end to create shipment
    }

    public function createInvoice($orderId)
    {
            // Code start to create invoice

            $order = $this->orderRepository->get($orderId);
            if ($order->canInvoice()) {
            $invoice = $this->invoiceService->prepareInvoice($order);
            $invoice->register();
            $invoice->save();
            $transactionSave = $this->transaction->addObject(
                $invoice
            )->addObject(
                $invoice->getOrder()
            );
            $transactionSave->save();
            $this->invoiceSender->send($invoice);
            //Send Invoice mail to customer
            $order->addStatusHistoryComment(
                __('Notified customer about invoice creation #%1.', $invoice->getId())
            )
                ->setIsCustomerNotified(true)
                ->save();
            }

            $writer = new Zend_Log_Writer_Stream(BP . '/var/log/delivered_order_status_updation.log');
            $logger = new Zend_Log();
            $logger->addWriter($writer);
        

            $objectManager = MagentoFrameworkAppObjectManager::getInstance();
            $order = $objectManager->create('MagentoSalesModelOrder')->load($orderId);
            $orderState = Order::STATE_PROCESSING;

            $logger->info('------------ Reached ---------');

            $order->setState($orderState)->setStatus($orderState);
            $order->save();
            // Code end to create invoice
    }