/** * Set inventory data to custom attribute * * @param Product $object * @return $this */ public function afterLoad($object) { $stockItem = $this->stockRegistry->getStockItem($object->getId(), $object->getStore()->getWebsiteId()); $object->setData($this->getAttribute()->getAttributeCode(), ['is_in_stock' => $stockItem->getIsInStock(), 'qty' => $stockItem->getQty()]); return parent::afterLoad($object); }
/** * {@inheritdoc} */ public function modifyData(array $data) { $fieldCode = 'quantity_and_stock_status'; $model = $this->locator->getProduct(); $modelId = $model->getId(); /** @var StockItemInterface $stockItem */ $stockItem = $this->stockRegistry->getStockItem($modelId, $model->getStore()->getWebsiteId()); $stockData = $modelId ? $this->getData($stockItem) : []; if (!empty($stockData)) { $data[$modelId][self::DATA_SOURCE_DEFAULT][self::STOCK_DATA_FIELDS] = $stockData; } if (isset($stockData['is_in_stock'])) { $data[$modelId][self::DATA_SOURCE_DEFAULT][$fieldCode]['is_in_stock'] = (int) $stockData['is_in_stock']; } if (!empty($this->stockConfiguration->getDefaultConfigValue(StockItemInterface::MIN_SALE_QTY))) { $minSaleQtyData = null; $defaultConfigValue = $this->stockConfiguration->getDefaultConfigValue(StockItemInterface::MIN_SALE_QTY); if (strpos($defaultConfigValue, 'a:') === 0) { // Set data source for dynamicRows Minimum Qty Allowed in Shopping Cart $minSaleQtyValue = unserialize($defaultConfigValue); foreach ($minSaleQtyValue as $group => $qty) { $minSaleQtyData[] = [StockItemInterface::CUSTOMER_GROUP_ID => $group, StockItemInterface::MIN_SALE_QTY => $qty]; } } else { $minSaleQtyData = $defaultConfigValue; } $path = $modelId . '/' . self::DATA_SOURCE_DEFAULT . '/stock_data/min_qty_allowed_in_shopping_cart'; $data = $this->arrayManager->set($path, $data, $minSaleQtyData); } return $data; }
/** * Copy product inventory data (used for product duplicate functionality) * * @param \Magento\Catalog\Model\Product $product * @param \Magento\Catalog\Model\Product $duplicate * @return void */ public function build(\Magento\Catalog\Model\Product $product, \Magento\Catalog\Model\Product $duplicate) { $stockData = ['use_config_min_qty' => 1, 'use_config_min_sale_qty' => 1, 'use_config_max_sale_qty' => 1, 'use_config_backorders' => 1, 'use_config_notify_stock_qty' => 1]; $currentStockItemDo = $this->stockRegistry->getStockItem($product->getId(), $product->getStore()->getWebsiteId()); if ($currentStockItemDo->getItemId()) { $stockData += ['use_config_enable_qty_inc' => $currentStockItemDo->getUseConfigEnableQtyInc(), 'enable_qty_increments' => $currentStockItemDo->getEnableQtyIncrements(), 'use_config_qty_increments' => $currentStockItemDo->getUseConfigQtyIncrements(), 'qty_increments' => $currentStockItemDo->getQtyIncrements()]; } $duplicate->setStockData($stockData); }
/** * Retrieve product qty increments * * @return float|false */ public function getProductQtyIncrements() { if ($this->_qtyIncrements === null) { $stockItem = $this->stockRegistry->getStockItem($this->getProduct()->getId(), $this->getProduct()->getStore()->getWebsiteId()); $this->_qtyIncrements = $stockItem->getQtyIncrements(); if (!$this->getProduct()->isSaleable()) { $this->_qtyIncrements = false; } } return $this->_qtyIncrements; }
/** * Add stock item information to the product's extension attributes * * @param \Magento\Catalog\Model\Product $product * @return \Magento\Catalog\Model\Product */ public function afterLoad(\Magento\Catalog\Model\Product $product) { $productExtension = $product->getExtensionAttributes(); if ($productExtension === null) { $productExtension = $this->productExtensionFactory->create(); } // stockItem := \Magento\CatalogInventory\Api\Data\StockItemInterface $productExtension->setStockItem($this->stockRegistry->getStockItem($product->getId())); $product->setExtensionAttributes($productExtension); return $product; }
/** * @param array $productsData * @dataProvider generateSimpleProductsWithPartialDataDataProvider * @magentoDbIsolation enabled */ public function testGenerateSimpleProductsWithPartialData($productsData) { $this->_product->setNewVariationsAttributeSetId(4); $generatedProducts = $this->_model->generateSimpleProducts($this->_product, $productsData); $parentStockItem = $this->stockRegistry->getStockItem($this->_product->getId()); foreach ($generatedProducts as $productId) { $stockItem = $this->stockRegistry->getStockItem($productId); $this->assertEquals($parentStockItem->getManageStock(), $stockItem->getManageStock()); $this->assertEquals('1', $stockItem->getIsInStock()); } }
/** * @param \Magento\Quote\Model\Quote $quote * @param \Magento\Catalog\Model\Product $product * @param \Magento\Framework\DataObject $config * @return \Magento\Quote\Model\Quote\Item|string */ public function init(\Magento\Quote\Model\Quote $quote, \Magento\Catalog\Model\Product $product, \Magento\Framework\DataObject $config) { $stockItem = $this->stockRegistry->getStockItem($product->getId(), $quote->getStore()->getWebsiteId()); if ($stockItem->getIsQtyDecimal()) { $product->setIsQtyDecimal(1); } else { $config->setQty((int) $config->getQty()); } $product->setCartQty($config->getQty()); $item = $quote->addProduct($product, $config, \Magento\Catalog\Model\Product\Type\AbstractType::PROCESS_MODE_FULL); return $item; }
/** * @param \Magento\Catalog\Block\Product\View $block * @param array $validators * @return array */ public function afterGetQuantityValidators(\Magento\Catalog\Block\Product\View $block, array $validators) { $stockItem = $this->stockRegistry->getStockItem($block->getProduct()->getId(), $block->getProduct()->getStore()->getWebsiteId()); $params = []; $params['minAllowed'] = max((double) $stockItem->getQtyMinAllowed(), 1); if ($stockItem->getQtyMaxAllowed()) { $params['maxAllowed'] = $stockItem->getQtyMaxAllowed(); } if ($stockItem->getQtyIncrements() > 0) { $params['qtyIncrements'] = (double) $stockItem->getQtyIncrements(); } $validators['validate-item-quantity'] = $params; return $validators; }
/** * {@inheritdoc} */ public function modifyData(array $data) { $fieldCode = 'quantity_and_stock_status'; $model = $this->locator->getProduct(); $modelId = $model->getId(); $stockItem = $this->stockRegistry->getStockItem($modelId, $model->getStore()->getWebsiteId()); $stockData = $stockItem->getData(); if (!empty($stockData)) { $data[$modelId][self::DATA_SOURCE_DEFAULT][self::STOCK_DATA_FIELDS] = $stockData; } if (isset($stockData['is_in_stock'])) { $data[$modelId][self::DATA_SOURCE_DEFAULT][$fieldCode]['is_in_stock'] = (int) $stockData['is_in_stock']; } return $this->prepareStockData($data); }
/** * Init stock item * * @param \Magento\Quote\Model\Quote\Item\Option $option * @param \Magento\Quote\Model\Quote\Item $quoteItem * * @return \Magento\CatalogInventory\Model\Stock\Item * @throws \Magento\Framework\Exception\LocalizedException */ public function getStockItem(\Magento\Quote\Model\Quote\Item\Option $option, \Magento\Quote\Model\Quote\Item $quoteItem) { $stockItem = $this->stockRegistry->getStockItem($option->getProduct()->getId(), $quoteItem->getStore()->getWebsiteId()); if (!$stockItem->getItemId()) { throw new \Magento\Framework\Exception\LocalizedException(__('The stock item for Product in option is not valid.')); } /** * define that stock item is child for composite product */ $stockItem->setIsChildItem(true); /** * don't check qty increments value for option product */ $stockItem->setSuppressCheckQtyIncrements(true); return $stockItem; }
/** * Check item product availability for reorder * * @param \Magento\Sales\Model\Order\Item $orderItem * @return boolean */ protected function isItemAvailableForReorder(\Magento\Sales\Model\Order\Item $orderItem) { try { $stockItem = $this->stockRegistry->getStockItem($orderItem->getProduct()->getId(), $orderItem->getStore()->getWebsiteId()); return $stockItem->getIsInStock(); } catch (\Magento\Framework\Exception\NoSuchEntityException $noEntityException) { return false; } }
/** * Return the stock item that needs to be updated. * If the stock item does not need to be updated, return null. * * @param \Magento\Catalog\Api\Data\ProductInterface $product * @return \Magento\CatalogInventory\Api\Data\StockItemInterface|null */ protected function getStockItemToBeUpdated($product) { // from the API, all the data we care about will exist as extension attributes of the original product $extendedAttributes = $product->getExtensionAttributes(); if ($extendedAttributes !== null) { $stockItem = $extendedAttributes->getStockItem(); if ($stockItem != null) { return $stockItem; } } // we have no new stock item information to update, however we need to ensure that the product does have some // stock item information present. On a newly created product, it will not have any stock item info. $stockItem = $this->stockRegistry->getStockItem($product->getId()); if ($stockItem->getItemId() != null) { // we already have stock item info, so we return null since nothing more needs to be updated return null; } return $stockItem; }
/** * Whether to show 'Return to stock' checkbox for item * * @param Item $item * @return bool */ public function canReturnItemToStock($item = null) { if (null !== $item) { if (!$item->hasCanReturnToStock()) { $stockItem = $this->stockRegistry->getStockItem($item->getOrderItem()->getProductId(), $item->getOrderItem()->getStore()->getWebsiteId()); $item->setCanReturnToStock($stockItem->getManageStock()); } return $item->getCanReturnToStock(); } return $this->canReturnToStock(); }
/** * Processing additional validation to check if carrier applicable. * * @param \Magento\Framework\Object $request * @return $this|bool|\Magento\Framework\Object * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function proccessAdditionalValidation(\Magento\Framework\Object $request) { //Skip by item validation if there is no items in request if (!count($this->getAllItems($request))) { return $this; } $maxAllowedWeight = (double) $this->getConfigData('max_package_weight'); $errorMsg = ''; $configErrorMsg = $this->getConfigData('specificerrmsg'); $defaultErrorMsg = __('The shipping module is not available.'); $showMethod = $this->getConfigData('showmethod'); /** @var $item \Magento\Quote\Model\Quote\Item */ foreach ($this->getAllItems($request) as $item) { $product = $item->getProduct(); if ($product && $product->getId()) { $weight = $product->getWeight(); $stockItemData = $this->stockRegistry->getStockItem($product->getId(), $item->getStore()->getWebsiteId()); $doValidation = true; if ($stockItemData->getIsQtyDecimal() && $stockItemData->getIsDecimalDivided()) { if ($stockItemData->getEnableQtyIncrements() && $stockItemData->getQtyIncrements()) { $weight = $weight * $stockItemData->getQtyIncrements(); } else { $doValidation = false; } } elseif ($stockItemData->getIsQtyDecimal() && !$stockItemData->getIsDecimalDivided()) { $weight = $weight * $item->getQty(); } if ($doValidation && $weight > $maxAllowedWeight) { $errorMsg = $configErrorMsg ? $configErrorMsg : $defaultErrorMsg; break; } } } if (!$errorMsg && !$request->getDestPostcode() && $this->isZipCodeRequired($request->getDestCountryId())) { $errorMsg = __('This shipping method is not available. Please specify the zip code.'); } if ($errorMsg && $showMethod) { $error = $this->_rateErrorFactory->create(); $error->setCarrier($this->_code); $error->setCarrierTitle($this->getConfigData('title')); $error->setErrorMessage($errorMsg); return $error; } elseif ($errorMsg) { return false; } return $this; }
/** * @param ProductInterface $product * @param StockItemInterface $stockItem * @throws LocalizedException * @return void */ private function validateStockItem(ProductInterface $product, StockItemInterface $stockItem) { $defaultScopeId = $this->stockConfiguration->getDefaultScopeId(); $defaultStockId = $this->stockRegistry->getStock($defaultScopeId)->getStockId(); $stockId = $stockItem->getStockId(); if ($stockId !== null && $stockId != $defaultStockId) { throw new LocalizedException(__('Invalid stock id: %1. Only default stock with id %2 allowed', $stockId, $defaultStockId)); } $stockItemId = $stockItem->getItemId(); if ($stockItemId !== null && (!is_numeric($stockItemId) || $stockItemId <= 0)) { throw new LocalizedException(__('Invalid stock item id: %1. Should be null or numeric value greater than 0', $stockItemId)); } $defaultStockItemId = $this->stockRegistry->getStockItem($product->getId())->getItemId(); if ($defaultStockItemId && $stockItemId !== null && $defaultStockItemId != $stockItemId) { throw new LocalizedException(__('Invalid stock item id: %1. Assigned stock item id is %2', $stockItemId, $defaultStockItemId)); } }
/** * Adds stock item qty to $items (creates new entry or increments existing one) * $items is array with following structure: * array( * $productId => array( * 'qty' => $qty, * 'item' => $stockItems|null * ) * ) * * @param QuoteItem $quoteItem * @param array &$items * @return void */ protected function _addItemToQtyArray(QuoteItem $quoteItem, &$items) { $productId = $quoteItem->getProductId(); if (!$productId) { return; } if (isset($items[$productId])) { $items[$productId] += $quoteItem->getTotalQty(); } else { $stockItem = null; if ($quoteItem->getProduct()) { /** @var Item $stockItem */ $stockItem = $this->stockRegistry->getStockItem($quoteItem->getProduct()->getId(), $quoteItem->getStore()->getWebsiteId()); } $items[$productId] = $quoteItem->getTotalQty(); } }
protected function _proccessCollection($quote, $storeId) { foreach ($quote->getAllVisibleItems() as $item) { $removeFromQuote = false; $product = $this->_objectManager->create('Magento\\Catalog\\Model\\Product')->load($item->getProductId()); if (!$product || $product->getStatus() == \Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED) { //Mage::log('AbandonedCart; ' . $product->getSku() . ' is no longer present or enabled; remove from quote ' . $quote->getId() . ' for email', null, 'Ebizmarts_AbandonedCart.log'); $removeFromQuote = true; } if ($product->getTypeId() == 'configurable') { $simpleProductId = $this->_objectManager->create('Magento\\Catalog\\Model\\Product')->getIdBySku($item->getSku()); $simpleProduct = $this->_objectManager->create('Magento\\Catalog\\Model\\Product') - load($simpleProductId); $stock = $simpleProduct->getStockItem(); $stockQty = $stock->getQty(); } elseif ($product->getTypeId() == 'bundle') { $options = $item->getProduct()->getTypeInstance(true)->getOrderOptions($item->getProduct()); $bundled_product = $this->_objectManager->create('\\Magento\\Catalog\\Model\\Product')->load($product->getId()); $selectionCollection = $bundled_product->getTypeInstance(true)->getSelectionsCollection($bundled_product->getTypeInstance(true)->getOptionsIds($bundled_product), $bundled_product); $stockQty = -1; foreach ($selectionCollection as $option) { foreach ($options['bundle_options'] as $bundle) { if ($bundle['value'][0]['title'] == $option->getName()) { $label = $bundle['label']; $qty = $bundle['value'][0]['qty']; if ($stockQty == -1 || $stockQty > $qty) { $stockQty = $qty; } } } } } else { $stock = $this->_stockRegistry->getStockItem($product->getGetId(), $storeId); //$product->getStockItem(); $stockQty = $stock->getQty(); } if (is_object($stock) && ($stock->getManageStock() || $stock->getUseConfigManageStock() && $this->_helper->getConfig('cataloginventory/item_options/manage_stock', $quote->getStoreId())) && $stockQty < $item->getQty()) { // Mage::log('AbandonedCart; ' . $product->getSku() . ' is no longer in stock; remove from quote ' . $quote->getId() . ' for email', null, 'Ebizmarts_AbandonedCart.log'); $removeFromQuote = true; } if ($removeFromQuote) { $quote->removeItem($item->getId()); } } }
/** * Prepare stock item data for save * * @param \Magento\Catalog\Model\Product $product * @return $this */ protected function saveStockItemData($product) { $stockItemData = $product->getStockData(); $stockItemData['product_id'] = $product->getId(); if (!isset($stockItemData['website_id'])) { $stockItemData['website_id'] = $this->stockConfiguration->getDefaultScopeId(); } $stockItemData['stock_id'] = $this->stockRegistry->getStock($stockItemData['website_id'])->getStockId(); foreach ($this->paramListToCheck as $dataKey => $configPath) { if (null !== $product->getData($configPath['item']) && null === $product->getData($configPath['config'])) { $stockItemData[$dataKey] = false; } } $originalQty = $product->getData('stock_data/original_inventory_qty'); if (strlen($originalQty) > 0) { $stockItemData['qty_correction'] = (isset($stockItemData['qty']) ? $stockItemData['qty'] : 0) - $originalQty; } // todo resolve issue with builder and identity field name $stockItem = $this->stockRegistry->getStockItem($stockItemData['product_id'], $stockItemData['website_id']); $stockItem->addData($stockItemData); $this->stockItemRepository->save($stockItem); return $this; }
/** * Update item in shopping cart (quote) * $requestInfo - either qty (int) or buyRequest in form of array or \Magento\Framework\Object * $updatingParams - information on how to perform update, passed to Quote->updateItem() method * * @param int $itemId * @param int|array|\Magento\Framework\Object $requestInfo * @param null|array|\Magento\Framework\Object $updatingParams * @return \Magento\Quote\Model\Quote\Item|string * @throws \Magento\Framework\Exception\LocalizedException * * @see \Magento\Quote\Model\Quote::updateItem() * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function updateItem($itemId, $requestInfo = null, $updatingParams = null) { try { $item = $this->getQuote()->getItemById($itemId); if (!$item) { throw new \Magento\Framework\Exception\LocalizedException(__('This quote item does not exist.')); } $productId = $item->getProduct()->getId(); $product = $this->_getProduct($productId); $request = $this->_getProductRequest($requestInfo); if ($productId) { $stockItem = $this->stockRegistry->getStockItem($productId, $product->getStore()->getWebsiteId()); $minimumQty = $stockItem->getMinSaleQty(); // If product was not found in cart and there is set minimal qty for it if ($minimumQty && $minimumQty > 0 && $request->getQty() < $minimumQty && !$this->getQuote()->hasProductId($productId)) { $request->setQty($minimumQty); } } $result = $this->getQuote()->updateItem($itemId, $request, $updatingParams); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->_checkoutSession->setUseNotice(false); $result = $e->getMessage(); } /** * We can get string if updating process had some errors */ if (is_string($result)) { if ($this->_checkoutSession->getUseNotice() === null) { $this->_checkoutSession->setUseNotice(true); } throw new \Magento\Framework\Exception\LocalizedException(__($result)); } $this->_eventManager->dispatch('checkout_cart_product_update_after', ['quote_item' => $result, 'product' => $product]); $this->_checkoutSession->setLastAddedProductId($productId); return $result; }
/** * Retrieve current product qty left in stock * * @return float */ public function getStockQtyLeft() { $stockItem = $this->stockRegistry->getStockItem($this->getProduct()->getId()); $minStockQty = $stockItem->getMinQty(); return $this->getStockQty() - $minStockQty; }
/** * Setup product for quote item * * @param \Magento\Catalog\Model\Product $product * @return $this */ public function setProduct($product) { if ($this->getQuote()) { $product->setStoreId($this->getQuote()->getStoreId()); $product->setCustomerGroupId($this->getQuote()->getCustomerGroupId()); } $this->setData('product', $product)->setProductId($product->getId())->setProductType($product->getTypeId())->setSku($this->getProduct()->getSku())->setName($product->getName())->setWeight($this->getProduct()->getWeight())->setTaxClassId($product->getTaxClassId())->setBaseCost($product->getCost()); $stockItem = $this->stockRegistry->getStockItem($product->getId(), $product->getStore()->getWebsiteId()); $this->setIsQtyDecimal($stockItem->getIsQtyDecimal()); $this->_eventManager->dispatch('sales_quote_item_set_product', ['product' => $product, 'quote_item' => $this]); return $this; }
/** * @param Product $product * @return float */ public function getProductStockQty(Product $product) { return $this->stockRegistry->getStockItem($product->getId(), $product->getStore()->getWebsiteId())->getQty(); }
/** * Checking if we can sale this bundle * * @param \Magento\Catalog\Model\Product $product * @return bool * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) */ public function isSalable($product) { if (!parent::isSalable($product)) { return false; } if ($product->hasData('all_items_salable')) { return $product->getData('all_items_salable'); } $optionCollection = $this->getOptionsCollection($product); if (!count($optionCollection->getItems())) { return false; } $requiredOptionIds = []; foreach ($optionCollection->getItems() as $option) { if ($option->getRequired()) { $requiredOptionIds[$option->getId()] = 0; } } $selectionCollection = $this->getSelectionsCollection($optionCollection->getAllIds(), $product); if (!count($selectionCollection->getItems())) { return false; } $salableSelectionCount = 0; foreach ($selectionCollection as $selection) { /* @var $selection \Magento\Catalog\Model\Product */ if ($selection->isSalable()) { $selectionEnoughQty = $this->_stockRegistry->getStockItem($selection->getId())->getManageStock() ? $selection->getSelectionQty() <= $this->_stockState->getStockQty($selection->getId()) : $selection->isInStock(); if (!$selection->hasSelectionQty() || $selection->getSelectionCanChangeQty() || $selectionEnoughQty) { $requiredOptionIds[$selection->getOptionId()] = 1; $salableSelectionCount++; } } } $isSalable = array_sum($requiredOptionIds) == count($requiredOptionIds) && $salableSelectionCount; $product->setData('all_items_salable', $isSalable); return $isSalable; }
/** * Stock item saving. * * @return $this */ protected function _saveStockItem() { $indexer = $this->indexerRegistry->get('catalog_product_category'); /** @var $stockResource \Magento\CatalogInventory\Model\ResourceModel\Stock\Item */ $stockResource = $this->_stockResItemFac->create(); $entityTable = $stockResource->getMainTable(); while ($bunch = $this->_dataSourceModel->getNextBunch()) { $stockData = []; $productIdsToReindex = []; // Format bunch to stock data rows foreach ($bunch as $rowNum => $rowData) { if (!$this->isRowAllowedToImport($rowData, $rowNum)) { continue; } $row = []; $row['product_id'] = $this->skuProcessor->getNewSku($rowData[self::COL_SKU])['entity_id']; $productIdsToReindex[] = $row['product_id']; $row['website_id'] = $this->stockConfiguration->getDefaultWebsiteId(); $row['stock_id'] = $this->stockRegistry->getStock($row['website_id'])->getStockId(); $stockItemDo = $this->stockRegistry->getStockItem($row['product_id'], $row['website_id']); $existStockData = $stockItemDo->getData(); $row = array_merge($this->defaultStockData, array_intersect_key($existStockData, $this->defaultStockData), array_intersect_key($rowData, $this->defaultStockData), $row); if ($this->stockConfiguration->isQty($this->skuProcessor->getNewSku($rowData[self::COL_SKU])['type_id'])) { $stockItemDo->setData($row); $row['is_in_stock'] = $this->stockStateProvider->verifyStock($stockItemDo); if ($this->stockStateProvider->verifyNotification($stockItemDo)) { $row['low_stock_date'] = $this->_localeDate->date(null, null, false)->format('Y-m-d H:i:s'); } $row['stock_status_changed_auto'] = (int) (!$this->stockStateProvider->verifyStock($stockItemDo)); } else { $row['qty'] = 0; } $stockData[] = $row; } // Insert rows if (!empty($stockData)) { $this->_connection->insertOnDuplicate($entityTable, $stockData); } if ($productIdsToReindex) { $indexer->reindexList($productIdsToReindex); } } return $this; }
/** * Checking availability of items with decimal qty * * @return bool */ public function hasItemsWithDecimalQty() { foreach ($this->getAllItems() as $item) { $stockItemDo = $this->stockRegistry->getStockItem($item->getProduct()->getId(), $item->getStore()->getWebsiteId()); if ($stockItemDo->getItemId() && $stockItemDo->getIsQtyDecimal()) { return true; } } return false; }
/** * Gets minimal sales quantity * * @param \Magento\Catalog\Model\Product $product * @return int|null */ public function getMinimalQty($product) { $stockItem = $this->stockRegistry->getStockItem($product->getId(), $product->getStore()->getWebsiteId()); $minSaleQty = $stockItem->getMinSaleQty(); return $minSaleQty > 0 ? $minSaleQty : null; }
public function getInventoryCount($item, $product) { $stockItem = $this->stockRegistry->getStockItem($product->getId(), $product->getStore()->getWebsiteId()); return $stockItem->getQty(); }
/** * Check product inventory data when quote item quantity declaring * * @param \Magento\Framework\Event\Observer $observer * * @return void * @throws \Magento\Framework\Exception\LocalizedException * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function validate(\Magento\Framework\Event\Observer $observer) { /* @var $quoteItem \Magento\Quote\Model\Quote\Item */ $quoteItem = $observer->getEvent()->getItem(); if (!$quoteItem || !$quoteItem->getProductId() || !$quoteItem->getQuote() || $quoteItem->getQuote()->getIsSuperMode()) { return; } $qty = $quoteItem->getQty(); /** @var \Magento\CatalogInventory\Model\Stock\Item $stockItem */ $stockItem = $this->stockRegistry->getStockItem($quoteItem->getProduct()->getId(), $quoteItem->getProduct()->getStore()->getWebsiteId()); /* @var $stockItem \Magento\CatalogInventory\Api\Data\StockItemInterface */ if (!$stockItem instanceof \Magento\CatalogInventory\Api\Data\StockItemInterface) { throw new \Magento\Framework\Exception\LocalizedException(__('The stock item for Product is not valid.')); } $parentStockItem = false; /** * Check if product in stock. For composite products check base (parent) item stock status */ if ($quoteItem->getParentItem()) { $product = $quoteItem->getParentItem()->getProduct(); $parentStockItem = $this->stockRegistry->getStockItem($product->getId(), $product->getStore()->getWebsiteId()); } if ($stockItem) { if (!$stockItem->getIsInStock() || $parentStockItem && !$parentStockItem->getIsInStock()) { $quoteItem->addErrorInfo('cataloginventory', \Magento\CatalogInventory\Helper\Data::ERROR_QTY, __('This product is out of stock.')); $quoteItem->getQuote()->addErrorInfo('stock', 'cataloginventory', \Magento\CatalogInventory\Helper\Data::ERROR_QTY, __('Some of the products are out of stock.')); return; } else { // Delete error from item and its quote, if it was set due to item out of stock $this->_removeErrorsFromQuoteAndItem($quoteItem, \Magento\CatalogInventory\Helper\Data::ERROR_QTY); } } /** * Check item for options */ if (($options = $quoteItem->getQtyOptions()) && $qty > 0) { $qty = $quoteItem->getProduct()->getTypeInstance()->prepareQuoteItemQty($qty, $quoteItem->getProduct()); $quoteItem->setData('qty', $qty); if ($stockItem) { $result = $this->stockState->checkQtyIncrements($quoteItem->getProduct()->getId(), $qty, $quoteItem->getProduct()->getStore()->getWebsiteId()); if ($result->getHasError()) { $quoteItem->addErrorInfo('cataloginventory', \Magento\CatalogInventory\Helper\Data::ERROR_QTY_INCREMENTS, $result->getMessage()); $quoteItem->getQuote()->addErrorInfo($result->getQuoteMessageIndex(), 'cataloginventory', \Magento\CatalogInventory\Helper\Data::ERROR_QTY_INCREMENTS, $result->getQuoteMessage()); } else { // Delete error from item and its quote, if it was set due to qty problems $this->_removeErrorsFromQuoteAndItem($quoteItem, \Magento\CatalogInventory\Helper\Data::ERROR_QTY_INCREMENTS); } } foreach ($options as $option) { $result = $this->optionInitializer->initialize($option, $quoteItem, $qty); if ($result->getHasError()) { $option->setHasError(true); $quoteItem->addErrorInfo('cataloginventory', \Magento\CatalogInventory\Helper\Data::ERROR_QTY, $result->getMessage()); $quoteItem->getQuote()->addErrorInfo($result->getQuoteMessageIndex(), 'cataloginventory', \Magento\CatalogInventory\Helper\Data::ERROR_QTY, $result->getQuoteMessage()); } else { // Delete error from item and its quote, if it was set due to qty lack $this->_removeErrorsFromQuoteAndItem($quoteItem, \Magento\CatalogInventory\Helper\Data::ERROR_QTY); } } } else { $result = $this->stockItemInitializer->initialize($stockItem, $quoteItem, $qty); if ($result->getHasError()) { $quoteItem->addErrorInfo('cataloginventory', \Magento\CatalogInventory\Helper\Data::ERROR_QTY, $result->getMessage()); $quoteItem->getQuote()->addErrorInfo($result->getQuoteMessageIndex(), 'cataloginventory', \Magento\CatalogInventory\Helper\Data::ERROR_QTY, $result->getQuoteMessage()); } else { // Delete error from item and its quote, if it was set due to qty lack $this->_removeErrorsFromQuoteAndItem($quoteItem, \Magento\CatalogInventory\Helper\Data::ERROR_QTY); } } }
/** * @return \Magento\CatalogInventory\Api\Data\StockItemInterface */ protected function loadSource() { return $this->stockRegistry->getStockItem($this->data['product_id']); }
public function testGetStockItem() { $this->assertEquals($this->stockItem, $this->stockRegistry->getStockItem($this->productId, $this->websiteId)); }