magento / inventory

Magento Inventory Project (a.k.a MSI)
Open Software License 3.0
337 stars 247 forks source link

Negative source item quantity not calculated in stock #3346

Open ioweb-gr opened 2 years ago

ioweb-gr commented 2 years ago

Preconditions (*)

  1. Magento 2.4.3-p1

Steps to reproduce (*)

Create at least 2 sources and add product X to those sources with the following quantities source1 -> qty = 2 / stock status = in stock source2 -> qty = -2 / stock status = out of stock

Another example

source1 -> qty = 2 source2 -> qty = 3 source3 -> qty = -29

  1. Reindex inventory

Expected result (*)

  1. The product shows a salable quantity of 0 and the product is not salable
  2. The product shows a salable quantity of -24 or 0 and the product is not salable

Actual result (*)

  1. The product is salable with 2 items
  2. The product is salable with 5 items in my case. image

It seems there is a condition in the select builder \Magento\InventoryIndexer\Indexer\SelectBuilder::execute

$quantityExpression = (string)$this->resourceConnection->getConnection()->getCheckSql(
            'source_item.' . SourceItemInterface::STATUS . ' = ' . SourceItemInterface::STATUS_OUT_OF_STOCK,
            0,
            SourceItemInterface::QUANTITY
        );

Which will actually force the qty to become 0 when the product is out of stock. This in turn makes the product appear salable when it really isn't. As to the reason why this source has negative quantities, it's because we also have a physical store which needs to sell, sometimes the physical shop can oversell because we can order the item from our supplier or move it internally between sources after talking with the customer. But this action is not allowed on the store.

Moreover the item may stay in this state for a while and Magento will cause overselling without any control. This condition is really wrong to force for detecting if a product is salable.

m2-assistant[bot] commented 2 years ago

Hi @ioweb-gr. Thank you for your report. To speed up processing of this issue, make sure that you provided sufficient information.

Add a comment to assign the issue: @magento I am working on this


ioweb-gr commented 2 years ago

I've been checking the code deeper to see why this is happening and this is probably done so that when a product is set to out of stock, positive quantities will be zeroed out more than negative quantities being zeroed out.

So I think that changing the condition from

SUM(IF(source_item.status = 0, 0, quantity))

to

SUM(IF(source_item.status = 0 AND source_item.quantity > 0, 0, quantity))

Would be enough to fix this bug.