/** * @param int|\Magento\Catalog\Model\Product $product * @param int $expectedIdCall * @dataProvider affectedProductsDataProvider */ public function testAroundApplyAllRulesToProduct($product, $expectedIdCall) { $this->_priceProcessorMock->expects($this->once())->method('reindexRow')->with($expectedIdCall); $ruleMock = $this->getMock('Magento\\CatalogRule\\Model\\Rule', array(), array(), '', false); $this->_model->aroundApplyToProduct($ruleMock, function () { }, $product); }
/** * 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 }
/** * Cancel order item * * @param EventObserver $observer * @return void */ public function execute(EventObserver $observer) { /** @var \Magento\Sales\Model\Order\Item $item */ $item = $observer->getEvent()->getItem(); $children = $item->getChildrenItems(); $qty = $item->getQtyOrdered() - max($item->getQtyShipped(), $item->getQtyInvoiced()) - $item->getQtyCanceled(); if ($item->getId() && $item->getProductId() && empty($children) && $qty) { $this->stockManagement->backItemQty($item->getProductId(), $qty, $item->getStore()->getWebsiteId()); } $this->priceIndexer->reindexRow($item->getProductId()); }
/** * Update product(s) status action * * @return \Magento\Backend\Model\View\Result\Redirect * @throws \Magento\Framework\Exception\LocalizedException|\Exception */ public function execute() { $productIds = (array) $this->getRequest()->getParam('product'); $storeId = (int) $this->getRequest()->getParam('store', 0); $status = (int) $this->getRequest()->getParam('status'); $this->_validateMassStatus($productIds, $status); $this->_objectManager->get('Magento\\Catalog\\Model\\Product\\Action')->updateAttributes($productIds, ['status' => $status], $storeId); $this->messageManager->addSuccess(__('A total of %1 record(s) have been updated.', count($productIds))); $this->_productPriceIndexerProcessor->reindexList($productIds); return $this->getDefaultResult(); }
/** * 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); }
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 testRefreshSpecialPrices() { $idsToProcess = [1, 2, 3]; $this->metadataPool->expects($this->atLeastOnce())->method('getMetadata')->willReturn($this->metadataMock); $this->metadataMock->expects($this->atLeastOnce())->method('getLinkField')->willReturn('row_id'); $this->metadataMock->expects($this->atLeastOnce())->method('getIdentifierField')->willReturn('entity_id'); $selectMock = $this->getMock('Magento\\Framework\\DB\\Select', [], [], '', false); $selectMock->expects($this->any())->method('from')->will($this->returnSelf()); $selectMock->expects($this->any())->method('joinLeft')->will($this->returnSelf()); $selectMock->expects($this->any())->method('where')->will($this->returnSelf()); $connectionMock = $this->getMock('Magento\\Framework\\DB\\Adapter\\AdapterInterface', [], [], '', false); $connectionMock->expects($this->any())->method('select')->will($this->returnValue($selectMock)); $connectionMock->expects($this->any())->method('fetchCol')->will($this->returnValue($idsToProcess)); $this->_resourceMock->expects($this->once())->method('getConnection')->will($this->returnValue($connectionMock)); $this->_resourceMock->expects($this->any())->method('getTableName')->will($this->returnValue('category')); $storeMock = $this->getMock('\\Magento\\Store\\Model\\Store', [], [], '', false); $storeMock->expects($this->any())->method('getId')->will($this->returnValue(1)); $this->_storeManagerMock->expects($this->once())->method('getStores')->with(true)->will($this->returnValue([$storeMock])); $this->_localeDateMock->expects($this->once())->method('scopeTimeStamp')->with($storeMock)->will($this->returnValue(32000)); $indexerMock = $this->getMock('Magento\\Indexer\\Model\\Indexer', [], [], '', false); $indexerMock->expects($this->exactly(2))->method('reindexList'); $this->_priceProcessorMock->expects($this->exactly(2))->method('getIndexer')->will($this->returnValue($indexerMock)); $attributeMock = $this->getMockForAbstractClass('Magento\\Eav\\Model\\Entity\\Attribute\\AbstractAttribute', [], '', false, true, true, ['__wakeup', 'getAttributeId']); $attributeMock->expects($this->any())->method('getAttributeId')->will($this->returnValue(1)); $this->_eavConfigMock->expects($this->any())->method('getAttribute')->will($this->returnValue($attributeMock)); $this->_model->execute(); }
/** * @magentoDbIsolation disabled * @magentoAppIsolation enabled * @magentoDataFixture Magento/Catalog/_files/price_row_fixture.php */ public function testProductsUpdate() { $this->_product->load(1); $this->_processor->reindexList([$this->_product->getId()]); $categoryFactory = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('Magento\\Catalog\\Model\\CategoryFactory'); $listProduct = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->get('Magento\\Catalog\\Block\\Product\\ListProduct'); $category = $categoryFactory->create()->load(9); $layer = $listProduct->getLayer(); $layer->setCurrentCategory($category); $productCollection = $layer->getProductCollection(); $this->assertEquals(1, $productCollection->count()); /** @var $product \Magento\Catalog\Model\Product */ foreach ($productCollection as $product) { $this->assertEquals($this->_product->getId(), $product->getId()); $this->assertEquals($this->_product->getPrice(), $product->getPrice()); } }
/** * Reindex affected products * * @param int $storeId * @param string $attrCode * @param \Zend_Db_Expr $attrConditionValue * @return void */ protected function _refreshSpecialPriceByStore($storeId, $attrCode, $attrConditionValue) { $attribute = $this->_eavConfig->getAttribute(\Magento\Catalog\Model\Product::ENTITY, $attrCode); $attributeId = $attribute->getAttributeId(); $connection = $this->_getConnection(); $select = $connection->select()->from($this->_resource->getTableName(['catalog_product_entity', 'datetime']), ['entity_id'])->where('attribute_id = ?', $attributeId)->where('store_id = ?', $storeId)->where('value = ?', $attrConditionValue); $this->_processor->getIndexer()->reindexList($connection->fetchCol($select, ['entity_id'])); }
/** * @magentoDbIsolation disabled * @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'); $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(); $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(10, $product->getPrice()); } }
/** * Update product(s) status action * * @return void */ public function execute() { $productIds = (array) $this->getRequest()->getParam('product'); $storeId = (int) $this->getRequest()->getParam('store', 0); $status = (int) $this->getRequest()->getParam('status'); try { $this->_validateMassStatus($productIds, $status); $this->_objectManager->get('Magento\\Catalog\\Model\\Product\\Action')->updateAttributes($productIds, array('status' => $status), $storeId); $this->messageManager->addSuccess(__('A total of %1 record(s) have been updated.', count($productIds))); $this->_productPriceIndexerProcessor->reindexList($productIds); } catch (\Magento\Core\Model\Exception $e) { $this->messageManager->addError($e->getMessage()); } catch (\Magento\Framework\Model\Exception $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->_getSession()->addException($e, __('Something went wrong while updating the product(s) status.')); } $this->_redirect('catalog/*/', array('store' => $storeId)); }
/** * @magentoDataFixture Magento/Catalog/_files/products.php * @magentoAppIsolation enabled */ public function testAddPriceDataOnSave() { $this->processor->getIndexer()->setScheduled(false); $this->assertFalse($this->processor->getIndexer()->isScheduled()); $productRepository = \Magento\TestFramework\Helper\Bootstrap::getObjectManager()->create('Magento\\Catalog\\Api\\ProductRepositoryInterface'); /** @var \Magento\Catalog\Api\Data\ProductInterface $product */ $product = $productRepository->get('simple'); $this->assertNotEquals(15, $product->getPrice()); $product->setPrice(15); $productRepository->save($product); $this->collection->addPriceData(0, 1); $this->collection->load(); /** @var \Magento\Catalog\Api\Data\ProductInterface[] $product */ $items = $this->collection->getItems(); /** @var \Magento\Catalog\Api\Data\ProductInterface $product */ $product = reset($items); $this->assertCount(2, $items); $this->assertEquals(15, $product->getPrice()); }
/** * Update product(s) status action * * @return \Magento\Backend\Model\View\Result\Redirect */ public function execute() { $productIds = (array) $this->getRequest()->getParam('product'); $storeId = (int) $this->getRequest()->getParam('store', 0); $status = (int) $this->getRequest()->getParam('status'); try { $this->_validateMassStatus($productIds, $status); $this->_objectManager->get('Magento\\Catalog\\Model\\Product\\Action')->updateAttributes($productIds, ['status' => $status], $storeId); $this->messageManager->addSuccess(__('A total of %1 record(s) have been updated.', count($productIds))); $this->_productPriceIndexerProcessor->reindexList($productIds); } catch (\Magento\Framework\Exception\LocalizedException $e) { $this->messageManager->addError($e->getMessage()); } catch (\Exception $e) { $this->_getSession()->addException($e, __('Something went wrong while updating the product(s) status.')); } /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */ $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT); return $resultRedirect->setPath('catalog/*/', ['store' => $storeId]); }
/** * Reindex affected products * * @param int $storeId * @param string $attrCode * @param \Zend_Db_Expr $attrConditionValue * @return void */ protected function _refreshSpecialPriceByStore($storeId, $attrCode, $attrConditionValue) { $attribute = $this->_eavConfig->getAttribute(\Magento\Catalog\Model\Product::ENTITY, $attrCode); $attributeId = $attribute->getAttributeId(); $linkField = $this->getMetadataPool()->getMetadata(CategoryInterface::class)->getLinkField(); $identifierField = $this->getMetadataPool()->getMetadata(CategoryInterface::class)->getIdentifierField(); $connection = $this->_getConnection(); $select = $connection->select()->from(['attr' => $this->_resource->getTableName(['catalog_product_entity', 'datetime'])], [$identifierField => 'cat.' . $identifierField])->joinLeft(['cat' => $this->_resource->getTableName('catalog_product_entity')], 'cat.' . $linkField . '= attr.' . $linkField, '')->where('attr.attribute_id = ?', $attributeId)->where('attr.store_id = ?', $storeId)->where('attr.value = ?', $attrConditionValue); $selectData = $connection->fetchCol($select, $identifierField); if (!empty($selectData)) { $this->_processor->getIndexer()->reindexList($selectData); } }
public function testRefreshSpecialPrices() { $idsToProcess = array(1, 2, 3); $selectMock = $this->getMock('Magento\\Framework\\DB\\Select', array(), array(), '', false); $selectMock->expects($this->any())->method('from')->will($this->returnSelf()); $selectMock->expects($this->any())->method('where')->will($this->returnSelf()); $connectionMock = $this->getMock('Magento\\Framework\\DB\\Adapter\\AdapterInterface', array(), array(), '', false); $connectionMock->expects($this->any())->method('select')->will($this->returnValue($selectMock)); $connectionMock->expects($this->any())->method('fetchCol')->with($selectMock, array('entity_id'))->will($this->returnValue($idsToProcess)); $this->_resourceMock->expects($this->once())->method('getConnection')->with('write')->will($this->returnValue($connectionMock)); $storeMock = $this->getMock('\\Magento\\Store\\Model\\Store', array(), array(), '', false); $storeMock->expects($this->any())->method('getId')->will($this->returnValue(1)); $this->_storeManagerMock->expects($this->once())->method('getStores')->with(true)->will($this->returnValue(array($storeMock))); $this->_localeDateMock->expects($this->once())->method('scopeTimeStamp')->with($storeMock)->will($this->returnValue(32000)); $indexerMock = $this->getMock('Magento\\Indexer\\Model\\Indexer', array(), array(), '', false); $indexerMock->expects($this->exactly(2))->method('reindexList'); $this->_priceProcessorMock->expects($this->exactly(2))->method('getIndexer')->will($this->returnValue($indexerMock)); $attributeMock = $this->getMockForAbstractClass('Magento\\Eav\\Model\\Entity\\Attribute\\AbstractAttribute', array(), '', false, true, true, array('__wakeup', 'getAttributeId')); $attributeMock->expects($this->any())->method('getAttributeId')->will($this->returnValue(1)); $this->_eavConfigMock->expects($this->any())->method('getAttribute')->will($this->returnValue($attributeMock)); $this->_model->refreshSpecialPrices(); }
public function testPriceReindexCallback() { $this->model = $this->objectManagerHelper->getObject('Magento\\Catalog\\Model\\Product', ['catalogProductType' => $this->productTypeInstanceMock, 'categoryIndexer' => $this->categoryIndexerMock, 'productFlatIndexerProcessor' => $this->productFlatProcessor, 'productPriceIndexerProcessor' => $this->productPriceProcessor, 'catalogProductOption' => $this->optionInstanceMock, 'resource' => $this->resource, 'registry' => $this->registry, 'categoryRepository' => $this->categoryRepository, 'data' => []]); $this->productPriceProcessor->expects($this->once())->method('reindexRow'); $this->assertNull($this->model->priceReindexCallback()); }
/** * Invalidate price indexer * * @param \Magento\Store\Model\ResourceModel\Website $subject * @param \Magento\Store\Model\ResourceModel\Website $result * @return \Magento\Store\Model\ResourceModel\Website * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function afterDelete(\Magento\Store\Model\ResourceModel\Website $subject, $result) { $this->_processor->markIndexerAsInvalid(); return $result; }
/** * 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())); }
/** * Init indexing process after product delete commit * * @return void */ protected function _afterDeleteCommit() { $this->reindex(); $this->_productPriceIndexerProcessor->reindexRow($this->getId()); parent::_afterDeleteCommit(); $this->_indexIndexer->indexEvents(self::ENTITY, \Magento\Index\Model\Event::TYPE_DELETE); }
public function testPriceReindexCallback() { $this->productPriceProcessor->expects($this->once())->method('reindexRow'); $this->assertNull($this->model->priceReindexCallback()); }
public function testAfterDelete() { $this->_priceProcessorMock->expects($this->once())->method('markIndexerAsInvalid'); $websiteMock = $this->getMock('Magento\\Store\\Model\\Resource\\Website', [], [], '', false); $this->assertEquals('return_value', $this->_model->afterDelete($websiteMock, 'return_value')); }
/** * Reindex product price * * @param int|\Magento\Catalog\Model\Product $product * * @return void */ protected function _reindexProduct($product) { $productId = is_numeric($product) ? $product : $product->getId(); $this->_processor->reindexRow($productId); }
/** * Cancel order item * * @param EventObserver $observer * @return $this */ public function cancelOrderItem($observer) { $item = $observer->getEvent()->getItem(); $children = $item->getChildrenItems(); $qty = $item->getQtyOrdered() - max($item->getQtyShipped(), $item->getQtyInvoiced()) - $item->getQtyCanceled(); if ($item->getId() && $item->getProductId() && empty($children) && $qty) { $this->_stock->backItemQty($item->getProductId(), $qty); } $this->_priceIndexer->reindexRow($item->getProductId()); return $this; }
/** * Init indexing process after product delete commit * * @return void */ public function afterDeleteCommit() { $this->reindex(); $this->_productPriceIndexerProcessor->reindexRow($this->getId()); parent::afterDeleteCommit(); }
/** * 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()]); }