public function testSave() { $params = []; $stockItemMock = $this->getMockBuilder('Magento\\CatalogInventory\\Api\\Data\\StockItemInterface')->disableOriginalConstructor()->getMock(); $this->indexProcessorMock->expects($this->any())->method('reindexRow')->withAnyParameters(); $this->assertInstanceOf('Magento\\CatalogInventory\\Api\\Data\\StockItemInterface', $this->model->save($stockItemMock, $params)); }
/** * @magentoDbIsolation enabled * @magentoAppIsolation enabled * @magentoDataFixture Magento/Catalog/_files/product_simple.php */ public function testProductUpdate() { $categoryFactory = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('\\Magento\\Catalog\\Model\\CategoryFactory'); /** @var \Magento\Catalog\Block\Product\ListProduct $listProduct */ $listProduct = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('\\Magento\\Catalog\\Block\\Product\\ListProduct'); /** @var \Magento\CatalogInventory\Model\Stock\Item $stockItem */ $stockItem = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('\\Magento\\CatalogInventory\\Model\\Stock\\Item'); $this->_processor->getIndexer()->setScheduled(false); $this->assertFalse($this->_processor->getIndexer()->isScheduled()); $stockItem->loadByProduct(1); $stockItem->addQty(11); $stockItem->save(); $category = $categoryFactory->create()->load(2); $layer = $listProduct->getLayer(); $layer->setCurrentCategory($category); $productCollection = $layer->getProductCollection(); $productCollection->joinField('qty', 'cataloginventory_stock_status', 'qty', 'product_id=entity_id', '{{table}}.stock_id=1', 'left'); $this->assertEquals(1, $productCollection->count()); /** @var $product \Magento\Catalog\Model\Product */ foreach ($productCollection as $product) { $this->assertEquals('Simple Product', $product->getName()); $this->assertEquals('Short description', $product->getShortDescription()); $this->assertEquals(111, $product->getQty()); } }
/** * After import handler * * @param \Magento\ImportExport\Model\Import $subject * @param Object $import * * @return mixed * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function afterImportSource(\Magento\ImportExport\Model\Import $subject, $import) { if (!$this->_stockndexerProcessor->isIndexerScheduled()) { $this->_stockndexerProcessor->markIndexerAsInvalid(); } return $import; }
/** * @magentoDbIsolation disabled * @magentoDataFixture Magento/Catalog/_files/product_simple.php */ public function testProductUpdate() { $categoryFactory = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\\Catalog\\Model\\CategoryFactory'); /** @var \Magento\Catalog\Block\Product\ListProduct $listProduct */ $listProduct = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\\Catalog\\Block\\Product\\ListProduct'); /** @var \Magento\Framework\Api\DataObjectHelper $dataObjectHelper */ $dataObjectHelper = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('\\Magento\\Framework\\Api\\DataObjectHelper'); /** @var \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry */ $stockRegistry = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\\CatalogInventory\\Api\\StockRegistryInterface'); /** @var \Magento\CatalogInventory\Api\StockItemRepositoryInterface $stockItemRepository */ $stockItemRepository = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\\CatalogInventory\\Api\\StockItemRepositoryInterface'); /** @var \Magento\CatalogInventory\Model\ResourceModel\Stock\Item $stockItemResource */ $stockItemResource = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\\CatalogInventory\\Model\\ResourceModel\\Stock\\Item'); $stockItem = $stockRegistry->getStockItem(1, 1); $stockItemData = ['qty' => $stockItem->getQty() + 12]; $dataObjectHelper->populateWithArray($stockItem, $stockItemData, '\\Magento\\CatalogInventory\\Api\\Data\\StockItemInterface'); $stockItemResource->setProcessIndexEvents(false); $stockItemRepository->save($stockItem); $this->_processor->reindexList([1]); $category = $categoryFactory->create()->load(2); $layer = $listProduct->getLayer(); $layer->setCurrentCategory($category); $productCollection = $layer->getProductCollection(); $productCollection->joinField('qty', 'cataloginventory_stock_status', 'qty', 'product_id=entity_id', '{{table}}.stock_id=1', 'left'); $this->assertEquals(1, $productCollection->count()); /** @var $product \Magento\Catalog\Model\Product */ foreach ($productCollection as $product) { $this->assertEquals('Simple Product', $product->getName()); $this->assertEquals('Short description', $product->getShortDescription()); $this->assertEquals(112, $product->getQty()); } }
/** * Return creditmemo items qty to stock * * @param EventObserver $observer * @return void */ public function execute(EventObserver $observer) { /* @var $creditmemo \Magento\Sales\Model\Order\Creditmemo */ $creditmemo = $observer->getEvent()->getCreditmemo(); $itemsToUpdate = []; foreach ($creditmemo->getAllItems() as $item) { $qty = $item->getQty(); if ($item->getBackToStock() && $qty || $this->stockConfiguration->isAutoReturnEnabled()) { $productId = $item->getProductId(); $parentItemId = $item->getOrderItem()->getParentItemId(); /* @var $parentItem \Magento\Sales\Model\Order\Creditmemo\Item */ $parentItem = $parentItemId ? $creditmemo->getItemByOrderId($parentItemId) : false; $qty = $parentItem ? $parentItem->getQty() * $qty : $qty; if (isset($itemsToUpdate[$productId])) { $itemsToUpdate[$productId] += $qty; } else { $itemsToUpdate[$productId] = $qty; } } } if (!empty($itemsToUpdate)) { $this->stockManagement->revertProductsSale($itemsToUpdate, $creditmemo->getStore()->getWebsiteId()); $updatedItemIds = array_keys($itemsToUpdate); $this->stockIndexerProcessor->reindexList($updatedItemIds); $this->priceIndexer->reindexList($updatedItemIds); } }
/** * Refresh stock index for specific stock items after successful order placement * * @param EventObserver $observer * @return void */ public function execute(EventObserver $observer) { // Reindex quote ids $quote = $observer->getEvent()->getQuote(); $productIds = []; foreach ($quote->getAllItems() as $item) { $productIds[$item->getProductId()] = $item->getProductId(); $children = $item->getChildrenItems(); if ($children) { foreach ($children as $childItem) { $productIds[$childItem->getProductId()] = $childItem->getProductId(); } } } if ($productIds) { $this->stockIndexerProcessor->reindexList($productIds); } // Reindex previously remembered items $productIds = []; foreach ($this->itemsForReindex->getItems() as $item) { $item->save(); $productIds[] = $item->getProductId(); } if (!empty($productIds)) { $this->priceIndexer->reindexList($productIds); } $this->itemsForReindex->clear(); // Clear list of remembered items - we don't need it anymore }
/** * Revert quote items inventory data (cover not success order place case) * * @param EventObserver $observer * @return void */ public function execute(EventObserver $observer) { $quote = $observer->getEvent()->getQuote(); $items = $this->productQty->getProductQty($quote->getAllItems()); $this->stockManagement->revertProductsSale($items, $quote->getStore()->getWebsiteId()); $productIds = array_keys($items); if (!empty($productIds)) { $this->stockIndexerProcessor->reindexList($productIds); $this->priceIndexer->reindexList($productIds); } // Clear flag, so if order placement retried again with success - it will be processed $quote->setInventoryProcessed(false); }
/** * Return creditmemo items qty to stock * * @param EventObserver $observer * @return void */ public function refundOrderInventory($observer) { /* @var $creditmemo \Magento\Sales\Model\Order\Creditmemo */ $creditmemo = $observer->getEvent()->getCreditmemo(); $itemsToUpdate = []; foreach ($creditmemo->getAllItems() as $item) { $qty = $item->getQty(); if ($item->getBackToStock() && $qty || $this->_catalogInventoryData->isAutoReturnEnabled()) { $productId = $item->getProductId(); $parentItemId = $item->getOrderItem()->getParentItemId(); /* @var $parentItem \Magento\Sales\Model\Order\Creditmemo\Item */ $parentItem = $parentItemId ? $creditmemo->getItemByOrderId($parentItemId) : false; $qty = $parentItem ? $parentItem->getQty() * $qty : $qty; if (isset($itemsToUpdate[$productId]['qty'])) { $itemsToUpdate[$productId]['qty'] += $qty; } else { $itemsToUpdate[$productId] = ['qty' => $qty, 'item' => null]; } } } if (!empty($itemsToUpdate)) { $this->_stock->revertProductsSale($itemsToUpdate); $updatedItemIds = array_keys($itemsToUpdate); $this->_stockIndexerProcessor->reindexList($updatedItemIds); $this->_priceIndexer->reindexList($updatedItemIds); } }
public function testRefundOrderInventory() { $websiteId = 0; $ids = ['1', '14']; $items = []; $isAutoReturnEnabled = true; $itemsToUpdate = []; foreach ($ids as $id) { $item = $this->getCreditMemoItem($id); $items[] = $item; $itemsToUpdate[$item->getProductId()] = $item->getQty(); } $creditMemo = $this->getMock('Magento\\Sales\\Model\\Order\\Creditmemo', [], [], '', false); $creditMemo->expects($this->once())->method('getAllItems')->will($this->returnValue($items)); $store = $this->getMock('Magento\\Store\\Model\\Store', ['getWebsiteId', '__wakeup'], [], '', false); $store->expects($this->once())->method('getWebsiteId')->will($this->returnValue($websiteId)); $creditMemo->expects($this->once())->method('getStore')->will($this->returnValue($store)); $this->stockConfiguration->expects($this->any())->method('isAutoReturnEnabled')->will($this->returnValue($isAutoReturnEnabled)); $this->stockManagement->expects($this->once())->method('revertProductsSale')->with($itemsToUpdate, $websiteId); $this->stockIndexerProcessor->expects($this->once())->method('reindexList')->with($ids); $this->priceIndexer->expects($this->once())->method('reindexList')->with($ids); $this->event->expects($this->once())->method('getCreditmemo')->will($this->returnValue($creditMemo)); $this->eventObserver->expects($this->atLeastOnce())->method('getEvent')->will($this->returnValue($this->event)); $this->observer->refundOrderInventory($this->eventObserver); }
public function testSave() { $productId = 1; $this->stockItemMock->expects($this->any())->method('getProductId')->willReturn($productId); $this->productMock->expects($this->once())->method('load')->with($productId)->willReturnSelf(); $this->productMock->expects($this->once())->method('getId')->willReturn($productId); $this->productMock->expects($this->once())->method('getTypeId')->willReturn('typeId'); $this->stockConfigurationMock->expects($this->once())->method('isQty')->with('typeId')->willReturn(true); $this->stockStateProviderMock->expects($this->once())->method('verifyStock')->with($this->stockItemMock)->willReturn(false); $this->stockItemMock->expects($this->once())->method('getManageStock')->willReturn(true); $this->stockItemMock->expects($this->once())->method('setIsInStock')->with(false)->willReturnSelf(); $this->stockItemMock->expects($this->once())->method('setStockStatusChangedAutomaticallyFlag')->with(true)->willReturnSelf(); $this->stockItemMock->expects($this->any())->method('setLowStockDate')->willReturnSelf(); $this->stockStateProviderMock->expects($this->once())->method('verifyNotification')->with($this->stockItemMock)->willReturn(true); $this->stockItemMock->expects($this->atLeastOnce())->method('setStockStatusChangedAuto')->willReturnSelf(); $this->stockItemMock->expects($this->once())->method('hasStockStatusChangedAutomaticallyFlag')->willReturn(true); $this->stockItemMock->expects($this->once())->method('getStockStatusChangedAutomaticallyFlag')->willReturn(true); $this->stockItemMock->expects($this->once())->method('getWebsiteId')->willReturn(1); $this->stockItemMock->expects($this->once())->method('setWebsiteId')->with(1)->willReturnSelf(); $this->stockItemMock->expects($this->once())->method('getStockId')->willReturn(1); $this->stockItemMock->expects($this->once())->method('setStockId')->with(1)->willReturnSelf(); $this->stockItemResourceMock->expects($this->once())->method('save')->with($this->stockItemMock)->willReturnSelf(); $this->indexProcessorMock->expects($this->once())->method('reindexRow')->with($productId); $this->assertEquals($this->stockItemMock, $this->model->save($this->stockItemMock)); }
/** * Reindex CatalogInventory save event * * @param AbstractModel $object * @return $this */ protected function _afterSave(AbstractModel $object) { parent::_afterSave($object); /** @var StockItemInterface $object */ if ($this->processIndexEvents) { $this->stockIndexerProcessor->reindexRow($object->getProductId()); } return $this; }
/** * @magentoDbIsolation enabled * @magentoAppIsolation enabled * @magentoDataFixture Magento/Catalog/_files/product_simple.php */ public function testReindexAll() { $this->_processor->reindexAll(); $categoryFactory = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('\\Magento\\Catalog\\Model\\CategoryFactory'); /** @var \Magento\Catalog\Block\Product\ListProduct $listProduct */ $listProduct = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('\\Magento\\Catalog\\Block\\Product\\ListProduct'); $category = $categoryFactory->create()->load(2); $layer = $listProduct->getLayer(); $layer->setCurrentCategory($category); $productCollection = $layer->getProductCollection(); $productCollection->joinField('qty', 'cataloginventory_stock_status_idx', 'qty', 'product_id=entity_id', '{{table}}.stock_id=1', 'left'); $this->assertCount(1, $productCollection); /** @var $product \Magento\Catalog\Model\Product */ foreach ($productCollection as $product) { $this->assertEquals('Simple Product', $product->getName()); $this->assertEquals('Short description', $product->getShortDescription()); $this->assertEquals(100, $product->getQty()); } }
public function testExecuteThatProductIdsAreObtainedFromAttributeHelper() { $this->attributeHelper->expects($this->any())->method('getProductIds')->will($this->returnValue([5])); $this->attributeHelper->expects($this->any())->method('getSelectedStoreId')->will($this->returnValue([1])); $this->inventoryHelper->expects($this->any())->method('getConfigItemOptions')->will($this->returnValue([])); $this->product->expects($this->any())->method('isProductsHasSku')->with([5])->will($this->returnValue(true)); $this->stockItemService->expects($this->any())->method('getStockItem')->with(5)->will($this->returnValue($this->stockItem)); $this->stockIndexerProcessor->expects($this->any())->method('reindexList')->with([5]); $this->request->expects($this->any())->method('getParam')->will($this->returnValueMap([['inventory', [], [7]]])); $this->messageManager->expects($this->never())->method('addError'); $this->messageManager->expects($this->never())->method('addException'); $this->object->execute(); }
public function testExecuteThatProductIdsAreObtainedFromAttributeHelper() { $this->attributeHelper->expects($this->any())->method('getProductIds')->will($this->returnValue([5])); $this->attributeHelper->expects($this->any())->method('getSelectedStoreId')->will($this->returnValue([1])); $this->attributeHelper->expects($this->any())->method('getStoreWebsiteId')->will($this->returnValue(1)); $this->stockConfig->expects($this->any())->method('getConfigItemOptions')->will($this->returnValue([])); $this->dataObjectHelperMock->expects($this->any())->method('populateWithArray')->with($this->stockItem, $this->anything(), '\\Magento\\CatalogInventory\\Api\\Data\\StockItemInterface')->willReturnSelf(); $this->product->expects($this->any())->method('isProductsHasSku')->with([5])->will($this->returnValue(true)); $this->stockItemService->expects($this->any())->method('getStockItem')->with(5, 1)->will($this->returnValue($this->stockItem)); $this->stockIndexerProcessor->expects($this->any())->method('reindexList')->with([5]); $this->request->expects($this->any())->method('getParam')->will($this->returnValueMap([['inventory', [], [7]]])); $this->messageManager->expects($this->never())->method('addError'); $this->messageManager->expects($this->never())->method('addException'); $this->object->execute(); }
public function testExecuteThatProductIdsAreObtainedFromAttributeHelper() { $this->attributeHelper->expects($this->any())->method('getProductIds')->will($this->returnValue([5])); $this->attributeHelper->expects($this->any())->method('getSelectedStoreId')->will($this->returnValue([1])); $this->attributeHelper->expects($this->any())->method('getStoreWebsiteId')->will($this->returnValue(1)); $this->stockConfig->expects($this->any())->method('getConfigItemOptions')->will($this->returnValue([])); $itemToSave = $this->getMockBuilder('Magento\\CatalogInventory\\Api\\Data\\StockItemInterface')->disableOriginalConstructor()->setMethods(['setItemId', 'save'])->getMockForAbstractClass(); $this->stockItemBuilder->expects($this->any())->method('mergeDataObjectWithArray')->withAnyParameters()->willReturnSelf(); $this->stockItemBuilder->expects($this->any())->method('create')->willReturn($itemToSave); $this->product->expects($this->any())->method('isProductsHasSku')->with([5])->will($this->returnValue(true)); $this->stockItemService->expects($this->any())->method('getStockItem')->with(5, 1)->will($this->returnValue($this->stockItem)); $this->stockIndexerProcessor->expects($this->any())->method('reindexList')->with([5]); $this->request->expects($this->any())->method('getParam')->will($this->returnValueMap([['inventory', [], [7]]])); $this->messageManager->expects($this->never())->method('addError'); $this->messageManager->expects($this->never())->method('addException'); $this->object->execute(); }
/** * @inheritdoc */ public function save(\Magento\CatalogInventory\Api\Data\StockItemInterface $stockItem) { try { /** @var \Magento\Catalog\Model\Product $product */ $product = $this->productFactory->create(); $product->load($stockItem->getProductId()); if (!$product->getId()) { return $stockItem; } $typeId = $product->getTypeId() ?: $product->getTypeInstance()->getTypeId(); $isQty = $this->stockConfiguration->isQty($typeId); if ($isQty) { $isInStock = $this->stockStateProvider->verifyStock($stockItem); if ($stockItem->getManageStock() && !$isInStock) { $stockItem->setIsInStock(false)->setStockStatusChangedAutomaticallyFlag(true); } // if qty is below notify qty, update the low stock date to today date otherwise set null $stockItem->setLowStockDate(null); if ($this->stockStateProvider->verifyNotification($stockItem)) { $stockItem->setLowStockDate((new \DateTime())->format('Y-m-d H:i:s')); } $stockItem->setStockStatusChangedAuto(0); if ($stockItem->hasStockStatusChangedAutomaticallyFlag()) { $stockItem->setStockStatusChangedAuto((int) $stockItem->getStockStatusChangedAutomaticallyFlag()); } } else { $stockItem->setQty(0); } $stockItem->setWebsiteId($stockItem->getWebsiteId()); $stockItem->setStockId($stockItem->getStockId()); $this->resource->save($stockItem); $this->indexProcessor->reindexRow($stockItem->getProductId()); } catch (\Exception $exception) { throw new CouldNotSaveException(__($exception->getMessage())); } return $stockItem; }
/** * Update product attributes * * @return void */ public function execute() { if (!$this->_validateProducts()) { return; } /* Collect Data */ $inventoryData = $this->getRequest()->getParam('inventory', array()); $attributesData = $this->getRequest()->getParam('attributes', array()); $websiteRemoveData = $this->getRequest()->getParam('remove_website_ids', array()); $websiteAddData = $this->getRequest()->getParam('add_website_ids', array()); /* Prepare inventory data item options (use config settings) */ $options = $this->_objectManager->get('Magento\\CatalogInventory\\Helper\\Data')->getConfigItemOptions(); foreach ($options as $option) { if (isset($inventoryData[$option]) && !isset($inventoryData['use_config_' . $option])) { $inventoryData['use_config_' . $option] = 0; } } try { if ($attributesData) { $dateFormat = $this->_objectManager->get('Magento\\Framework\\Stdlib\\DateTime\\TimezoneInterface')->getDateFormat(\Magento\Framework\Stdlib\DateTime\TimezoneInterface::FORMAT_TYPE_SHORT); $storeId = $this->attributeHelper->getSelectedStoreId(); foreach ($attributesData as $attributeCode => $value) { $attribute = $this->_objectManager->get('Magento\\Eav\\Model\\Config')->getAttribute(\Magento\Catalog\Model\Product::ENTITY, $attributeCode); if (!$attribute->getAttributeId()) { unset($attributesData[$attributeCode]); continue; } if ($attribute->getBackendType() == 'datetime') { if (!empty($value)) { $filterInput = new \Zend_Filter_LocalizedToNormalized(array('date_format' => $dateFormat)); $filterInternal = new \Zend_Filter_NormalizedToLocalized(array('date_format' => \Magento\Framework\Stdlib\DateTime::DATE_INTERNAL_FORMAT)); $value = $filterInternal->filter($filterInput->filter($value)); } else { $value = null; } $attributesData[$attributeCode] = $value; } elseif ($attribute->getFrontendInput() == 'multiselect') { // Check if 'Change' checkbox has been checked by admin for this attribute $isChanged = (bool) $this->getRequest()->getPost($attributeCode . '_checkbox'); if (!$isChanged) { unset($attributesData[$attributeCode]); continue; } if (is_array($value)) { $value = implode(',', $value); } $attributesData[$attributeCode] = $value; } } $this->_objectManager->get('Magento\\Catalog\\Model\\Product\\Action')->updateAttributes($this->attributeHelper->getProductIds(), $attributesData, $storeId); } if ($inventoryData) { /** @var \Magento\CatalogInventory\Service\V1\StockItemService $stockItemService */ $stockItemService = $this->_objectManager->create('Magento\\CatalogInventory\\Service\\V1\\StockItemService'); foreach ($this->_helper->getProductIds() as $productId) { $stockItemDo = $stockItemService->getStockItem($productId); if (!$stockItemDo->getProductId()) { $inventoryData[] = $productId; } $stockItemService->saveStockItem($this->stockItemBuilder->mergeDataObjectWithArray($stockItemDo, $inventoryData)); } $this->_stockIndexerProcessor->reindexList($this->_helper->getProductIds()); } if ($websiteAddData || $websiteRemoveData) { /* @var $actionModel \Magento\Catalog\Model\Product\Action */ $actionModel = $this->_objectManager->get('Magento\\Catalog\\Model\\Product\\Action'); $productIds = $this->attributeHelper->getProductIds(); if ($websiteRemoveData) { $actionModel->updateWebsites($productIds, $websiteRemoveData, 'remove'); } if ($websiteAddData) { $actionModel->updateWebsites($productIds, $websiteAddData, 'add'); } $this->_eventManager->dispatch('catalog_product_to_website_change', array('products' => $productIds)); $this->messageManager->addNotice(__('Please refresh "Catalog URL Rewrites" and "Product Attributes" in System -> ' . '<a href="%1">Index Management</a>.', $this->getUrl('adminhtml/process/list'))); } $this->messageManager->addSuccess(__('A total of %1 record(s) were updated.', count($this->attributeHelper->getProductIds()))); $this->_productFlatIndexerProcessor->reindexList($this->attributeHelper->getProductIds()); if ($this->_catalogProduct->isDataForPriceIndexerWasChanged($attributesData) || !empty($websiteRemoveData) || !empty($websiteAddData)) { $this->_productPriceIndexerProcessor->reindexList($this->attributeHelper->getProductIds()); } } catch (\Magento\Framework\Model\Exception $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addException($e, __('Something went wrong while updating the product(s) attributes.')); } $this->_redirect('catalog/product/', array('store' => $this->attributeHelper->getSelectedStoreId())); }
/** * @dataProvider saveAndRebuildIndexDataProvider * * @param int $newStockValue new value for stock status * @param int $callCount count matcher */ public function testSaveAndRebuildIndex($newStockValue, $callCount) { $this->model->setValue($newStockValue); $this->stockIndexerProcessor->expects($this->exactly($callCount))->method('markIndexerAsInvalid'); $this->model->afterSave(); }
/** * Before save handler * * @param \Magento\Store\Model\ResourceModel\Group $subject * @param \Magento\Framework\Model\AbstractModel $object * * @return void * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function beforeSave(\Magento\Store\Model\ResourceModel\Group $subject, \Magento\Framework\Model\AbstractModel $object) { if (!$object->getId() || $object->dataHasChangedFor('website_id')) { $this->_indexerProcessor->markIndexerAsInvalid(); } }
/** * Update product attributes * * @return \Magento\Backend\Model\View\Result\Redirect * @SuppressWarnings(PHPMD.CyclomaticComplexity) * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function execute() { if (!$this->_validateProducts()) { return $this->resultRedirectFactory->create()->setPath('catalog/product/', ['_current' => true]); } /* Collect Data */ $inventoryData = $this->getRequest()->getParam('inventory', []); $attributesData = $this->getRequest()->getParam('attributes', []); $websiteRemoveData = $this->getRequest()->getParam('remove_website_ids', []); $websiteAddData = $this->getRequest()->getParam('add_website_ids', []); /* Prepare inventory data item options (use config settings) */ $options = $this->_objectManager->get('Magento\\CatalogInventory\\Api\\StockConfigurationInterface')->getConfigItemOptions(); foreach ($options as $option) { if (isset($inventoryData[$option]) && !isset($inventoryData['use_config_' . $option])) { $inventoryData['use_config_' . $option] = 0; } } try { $storeId = $this->attributeHelper->getSelectedStoreId(); if ($attributesData) { $dateFormat = $this->_objectManager->get('Magento\\Framework\\Stdlib\\DateTime\\TimezoneInterface')->getDateFormat(\IntlDateFormatter::SHORT); foreach ($attributesData as $attributeCode => $value) { $attribute = $this->_objectManager->get('Magento\\Eav\\Model\\Config')->getAttribute(\Magento\Catalog\Model\Product::ENTITY, $attributeCode); if (!$attribute->getAttributeId()) { unset($attributesData[$attributeCode]); continue; } if ($attribute->getBackendType() == 'datetime') { if (!empty($value)) { $filterInput = new \Zend_Filter_LocalizedToNormalized(['date_format' => $dateFormat]); $filterInternal = new \Zend_Filter_NormalizedToLocalized(['date_format' => \Magento\Framework\Stdlib\DateTime::DATE_INTERNAL_FORMAT]); $value = $filterInternal->filter($filterInput->filter($value)); } else { $value = null; } $attributesData[$attributeCode] = $value; } elseif ($attribute->getFrontendInput() == 'multiselect') { // Check if 'Change' checkbox has been checked by admin for this attribute $isChanged = (bool) $this->getRequest()->getPost($attributeCode . '_checkbox'); if (!$isChanged) { unset($attributesData[$attributeCode]); continue; } if (is_array($value)) { $value = implode(',', $value); } $attributesData[$attributeCode] = $value; } } $this->_objectManager->get('Magento\\Catalog\\Model\\Product\\Action')->updateAttributes($this->attributeHelper->getProductIds(), $attributesData, $storeId); } if ($inventoryData) { // TODO why use ObjectManager? /** @var \Magento\CatalogInventory\Api\StockRegistryInterface $stockRegistry */ $stockRegistry = $this->_objectManager->create('Magento\\CatalogInventory\\Api\\StockRegistryInterface'); /** @var \Magento\CatalogInventory\Api\StockItemRepositoryInterface $stockItemRepository */ $stockItemRepository = $this->_objectManager->create('Magento\\CatalogInventory\\Api\\StockItemRepositoryInterface'); foreach ($this->attributeHelper->getProductIds() as $productId) { $stockItemDo = $stockRegistry->getStockItem($productId, $this->attributeHelper->getStoreWebsiteId($storeId)); if (!$stockItemDo->getProductId()) { $inventoryData[] = $productId; } $stockItemId = $stockItemDo->getId(); $this->dataObjectHelper->populateWithArray($stockItemDo, $inventoryData, '\\Magento\\CatalogInventory\\Api\\Data\\StockItemInterface'); $stockItemDo->setItemId($stockItemId); $stockItemRepository->save($stockItemDo); } $this->_stockIndexerProcessor->reindexList($this->attributeHelper->getProductIds()); } if ($websiteAddData || $websiteRemoveData) { /* @var $actionModel \Magento\Catalog\Model\Product\Action */ $actionModel = $this->_objectManager->get('Magento\\Catalog\\Model\\Product\\Action'); $productIds = $this->attributeHelper->getProductIds(); if ($websiteRemoveData) { $actionModel->updateWebsites($productIds, $websiteRemoveData, 'remove'); } if ($websiteAddData) { $actionModel->updateWebsites($productIds, $websiteAddData, 'add'); } $this->_eventManager->dispatch('catalog_product_to_website_change', ['products' => $productIds]); } $this->messageManager->addSuccess(__('A total of %1 record(s) were updated.', count($this->attributeHelper->getProductIds()))); $this->_productFlatIndexerProcessor->reindexList($this->attributeHelper->getProductIds()); if ($this->_catalogProduct->isDataForPriceIndexerWasChanged($attributesData) || !empty($websiteRemoveData) || !empty($websiteAddData)) { $this->_productPriceIndexerProcessor->reindexList($this->attributeHelper->getProductIds()); } } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->messageManager->addException($e, __('Something went wrong while updating the product(s) attributes.')); } return $this->resultRedirectFactory->create()->setPath('catalog/product/', ['store' => $this->attributeHelper->getSelectedStoreId()]); }
/** * Reindex CatalogInventory save event * * @return $this */ protected function _afterSave() { parent::_afterSave(); if ($this->_processIndexEvents) { $this->_stockIndexerProcessor->reindexRow($this->getProductId()); } return $this; }