/**
  * 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
 }
Beispiel #3
0
 /**
  * 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);
 }
Beispiel #5
0
 /**
  * @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());
     }
 }
Beispiel #6
0
 /**
  * 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]);
 }
Beispiel #7
0
 /**
  * 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));
 }
Beispiel #8
0
 /**
  * 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()]);
 }
Beispiel #9
0
 /**
  * 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);
     }
 }
Beispiel #10
0
 /**
  * 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()));
 }