1

I have a script that creates orders in Magento 2.

<?php
/**
 * ExtendedRma Helper
 */
namespace Company\Module\Helper;

class CreateOrder extends \Magento\Framework\App\Helper\AbstractHelper
{
    protected $invoiceService;
    protected $transaction;
    protected $invoiceSender;

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        \Magento\Store\Model\StoreManagerInterface $storeManager,
        \Magento\Customer\Model\CustomerFactory $customerFactory,
        \Magento\Catalog\Api\ProductRepositoryInterface $productRepository,
        \Magento\Customer\Api\CustomerRepositoryInterface $customerRepository,
        \Magento\Quote\Model\QuoteFactory $quote,
        \Magento\Quote\Model\QuoteManagement $quoteManagement,
        \Magento\Sales\Model\Order\Email\Sender\OrderSender $orderSender,
        \Magento\Quote\Model\Quote\Address\Rate $shippingRate,
        \Magento\Sales\Model\Service\InvoiceService $invoiceService,
        \Magento\Framework\DB\Transaction $transaction,
        \Magento\Sales\Model\Order\Email\Sender\InvoiceSender $invoiceSender,
    \Magento\Catalog\Helper\Product $productHelper
    )
    {
        $this->storeManager = $storeManager;
        $this->customerFactory = $customerFactory;
        $this->productRepository = $productRepository;
        $this->customerRepository = $customerRepository;
        $this->quote = $quote;
        $this->quoteManagement = $quoteManagement;
        $this->orderSender = $orderSender;
        $this->shippingRate = $shippingRate;
        $this->invoiceService = $invoiceService;
        $this->transaction = $transaction;
        $this->invoiceSender = $invoiceSender;
        $productHelper->setSkipSaleableCheck(true);
        parent::__construct($context);
    }

    /*
    * create order programmatically
    */
    public function createOrder($orderInfo)
    {
        $store = $this->storeManager->getStore();
        $storeId = $store->getStoreId();
        $websiteId = $this->storeManager->getStore()->getWebsiteId();
        $quote = $this->quote->create(); //Create object of quote
        $quote->setStore($store); //set store for our quote
        /* for registered customer */
        $customer = $this->customerRepository->getById($orderInfo['customer_id']);
        $quote->setCurrency();
        $quote->assignCustomer($customer); //Assign quote to customer

        //add items in quote
        foreach ($orderInfo['items'] as $item) {
            $product = $this->productRepository->getById($item['product_id']);
            if (!empty($item['super_attribute'])) {
                /* for configurable product */
                $buyRequest = new \Magento\Framework\DataObject($item);
                $quote->addProduct($product, $buyRequest);
            } else {
                /* for simple product */
                $product->setPrice($item['custom_price']);
                $quote->addProduct($product, intval($item['qty']));
            }
        }

        //Set Billing and shipping Address to quote
        $quote->getBillingAddress()->addData($orderInfo['shipping_address'])->setCustomerAddressId(null);
        $quote->getShippingAddress()->addData($orderInfo['shipping_address'])->setCustomerAddressId(null);

        // set shipping method
        $quote->getShippingAddress()->setCollectShippingRates(true)
                                    ->setShippingMethod('freeshipping_freeshipping')
                                    ->collectShippingRates();

        $quote->setPaymentMethod('checkmo'); //payment method, please verify checkmo must be enable from admin
        $quote->setInventoryProcessed(false); //decrease item stock equal to qty
        $quote->save(); //quote save
        // Set Sales Order Payment, We have taken check/money order
        $quote->getPayment()->importData(['method' => 'checkmo']);

        // Collect Quote Totals & Save
        $quote->collectTotals();
        $quote->setCreatedAt($orderInfo['date_added'])->save();
        // Create Order From Quote Object
        $order = $this->quoteManagement->submit($quote);

        $order->setCreatedAt($orderInfo['date_added']);

        if($orderInfo['order_status'] == 'Delivered' || $orderInfo['order_status'] == 'Dispatched' || $orderInfo['order_status'] == 'Billed' || $orderInfo['order_status' == 'Transferred']){
            $this->createInvoice($order);
        }

        switch ($orderInfo['order_status']){
            case 'Pending':
                $orderStatus = 'pending';
                $orderState = 'new';
                break;
            case 'Complete':
                $orderStatus = 'pending';
                $orderState = 'new';
                break;
            case 'Processed':
                $orderStatus = 'confirmed';
                $orderState = 'new';
                break;
            case 'Billed':
                $orderStatus = 'billed';
                $orderState = 'processing';
                break;
            case 'Transferred':
                $orderStatus = 'transferred';
                $orderState = 'processing';
                break;
            case 'Dispatched':
                $orderStatus = 'dispatched';
                $orderState = 'processing';
                break;
            case 'Delivered':
                $orderStatus = 'delivered';
                $orderState = 'complete';
                break;
            case 'Product Missing':
                $orderStatus = 'product_missing';
                $orderState = 'holded';
                break;
        }

        $order->setStatus($orderStatus)->setState($orderState);
        $order->addStatusHistoryComment(__('Order Migrated from old system:old orderId #%1.',$orderInfo['old_order_id']))->setIsCustomerNotified(false);
        $order->save();
        /* for send order email to customer email id */
        //$this->orderSender->send($order);
        /* get order real id from order */
        $orderId = $order->getIncrementId();
        if ($orderId) {
            $result['success'] = $orderId;
        } else {
            $result = ['error' => true, 'msg' => 'Error occurs for Order placed'];
        }
        return $result;
    }

    public function createInvoice($order){
        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 notification code
            $order->addStatusHistoryComment(
                __('Invoice created #%1.', $invoice->getId())
            )
                ->setIsCustomerNotified(false)
                ->save();
        }
    }
}

I have another php code that calls the above function createOrder in a loop of over 10000.

Now the issue is, at start it creates order at around 100 orders/minute, over the time the average reduces to around 30 orders/minute.

If an order at start has 10 items in it, then it completes at faster rate then an order after couple of minutes, having 1-2 items.

Does PHP slows down over time or Magento indexes something due to which order creation slows down?

Your Answer

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

Browse other questions tagged or ask your own question.