Question

We want to update and check product quantity when user clicks on "Place Order" button. If product is outofstock in remote API and get 0 qty then user should not able to "Place Order" and display default error message.

Default Magento works that way and show message if we update qty through backend while customer is on "Place Order".

Please suggest.

Was it helpful?

Solution

You can create a custom extension with following 2 files.

etc/di.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">s
    <type name="Magento\Checkout\Model\PaymentInformationManagement">
        <plugin name="update_qty_from_api" type="{Vendor}\{Module}\Plugin\UpdateQtyFromApi" />
    </type>
</config>

Plugin/UpdateQtyFromApi.php

<?php

namespace {Vendor}\{Module}\Plugin;

use Magento\Quote\Model\QuoteFactory;

class UpdateQtyFromApi
{
    public function __construct(
        QuoteFactory $quoteFactory,
        \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry
    ) {
        $this->quoteFactory = $quoteFactory;
        $this->stockRegistry = $stockRegistry;
    }

    public function beforeSavePaymentInformationAndPlaceOrder(
        $subject,
        $cartId,
        \Magento\Quote\Api\Data\PaymentInterface $paymentMethod,
        \Magento\Quote\Api\Data\AddressInterface $billingAddress = null
    )
    {
        $this->callApi($cartId);

        return [$cartId, $paymentMethod, $billingAddress];
    }

    public function callApi($cartId)
    {
        $quote = $this->quoteFactory->create()->load($cartId);

        $quoteItems = $quote->getAllItems();

        foreach ($quoteItems as $item) {
            $sku = $item->getProduct()->getSku();
            $qty = $this->getQtyFromCurlCall($sku);

            $this->updateQty($sku, $qty);
        }
    }

    public function getQtyFromCurlCall($sku)
    {
        // make your curl call here to get qty based on sku, and return that qty
        return 0;
    }

    public function updateQty($sku, $qty)
    {
        $stockItem = $this->stockRegistry->getStockItemBySku($sku);
        $stockItem->setQty($qty);
        $stockItem->setIsInStock((bool)$qty);
        $this->stockRegistry->updateStockItemBySku($sku, $stockItem);
    }
}

Replace {Vendor} and {Module} with your actual vendor and module name. And also add your condition accordingly in code. This will not allow user to place order if your condition does not match with your API.

Hope this helps you !!!

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top