elgentos / magento2-inventory-log

Magento 2 - Inventory Log
29 stars 11 forks source link

Error updating product stock through rest API #21

Open robsoned opened 2 months ago

robsoned commented 2 months ago

Error updating product stock through rest API

Preconditions

  1. Magento 2.4.7
  2. PHP 8.3

Steps to reproduce

  1. Try to update a product stock from the rest API.
  2. Request example: PUT: /rest/all/V1/products/24-MB01 Body:

    {
        "product": {
            "extension_attributes": {            
                "stock_item": {
                    "qty": 201,
                    "isInStock": true
               }            
            }
        }
    }

Expected result

  1. The product stock is updated successfully.

Actual result

  1. An error code 400 is returned with the message: The product was unable to be saved. Please try again.

#

After some debugging, I found out what was happening. As the error message is not very clear about the problem itself, and there was no other information about the error being logged to the log files. I found where the exception was being thrown and just added the actual error message to the exception:

#

With that change the error message now returns: The product was unable to be saved. Please try again.Registry key \"movement_section\" already exists

The error occurs on vendor/elgentos/magento2-inventory-log/Plugin/Webapi/Stock/StockItemRepository.php at line 20. If I comment out the register->register() method. The product stock is updated successfully, but it means that the registration of the movement_section key has already been set before the beforeSave() method was called. We can see on the screenshot below, that the the last two records have the message indicating that this stock update was made manually, but it was made through the rest API.

#

After a little more digging, I found out that the registration of the movement_section key is happening at /vendor/elgentos/magento2-inventory-log/Observer/SaveInventoryDataObserver.php. Configured under etc/events.xml:

    <config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">

        <event name="catalog_product_save_before">

            <observer name="kiwicommerce_inventory" instance="Elgentos\InventoryLog\Observer\SaveInventoryDataObserver"/>        

        </event>
    ...