0

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('Magento\Sales\Model\Order')
            ->load($orderId);

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

            // Initialize the order shipment object
            $convertOrder = $this->_objectManager->create('Magento\Sales\Model\Convert\Order');
            $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('Magento\Shipping\Model\ShipmentNotifier')
                    ->notify($shipment);

                $shipment->save();
            } catch (\Exception $e) {
                throw new \Magento\Framework\Exception\LocalizedException(
                                __($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 = \Magento\Framework\App\ObjectManager::getInstance();
            $order = $objectManager->create('\Magento\Sales\Model\Order')->load($orderId);
            $orderState = Order::STATE_PROCESSING;

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

            $order->setState($orderState)->setStatus($orderState);
            $order->save();
            // Code end to create invoice
    }
2
  • share your code what you are trying? Feb 13, 2023 at 7:03
  • @DhirenVasoya added
    – Arjun
    Feb 13, 2023 at 7:09

1 Answer 1

0

Your code need to look like this.

public function execute()
{
        $api_response_array = [22,23];
       
        foreach ($api_response_array as $OrderId) 
        {
           $collection = $this->_orderCollectionFactory->create()
               ->addAttributeToSelect('entity_id')
               ->addAttributeToSelect('status')
               ->addFieldToFilter('entity_id',$OrderId);

            $orderstatus = '';

            foreach ($collection->getData() as $Orderdata) 
            {
                  $orderstatus = $Orderdata['status'];
            }

            if ((!empty($orderstatus)) && ($orderstatus == 'pending')) 
            {
                $this->createInvoice($OrderId);
                $this->createShipment($OrderId);
            } 
            if ((!empty($orderstatus)) && ($orderstatus == 'processing') 
            {
                 $this->createShipment($OrderId);
            }
        }
}
1
  • Thanks @Dhiren.. I will try it.
    – Arjun
    Feb 13, 2023 at 13:39

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.