/**
  * Products collection.
  *
  * @return array
  */
 public function getLoadedProductCollection()
 {
     $productsToDisplay = [];
     $mode = $this->getRequest()->getActionName();
     $customerId = $this->getRequest()->getParam('customer_id');
     $limit = $this->recommnededHelper->getDisplayLimitByMode($mode);
     //login customer to receive the recent products
     $session = $this->sessionFactory->create();
     $isLoggedIn = $session->loginById($customerId);
     $collection = $this->viewed;
     $productItems = $collection->getItemsCollection()->setPageSize($limit);
     //get the product ids from items collection
     $productIds = $productItems->getColumnValues('product_id');
     //get product collection to check for salable
     $productCollection = $this->productFactory->create()->getCollection()->addAttributeToSelect('*')->addFieldToFilter('entity_id', ['in' => $productIds]);
     //show products only if is salable
     foreach ($productCollection as $product) {
         if ($product->isSalable()) {
             $productsToDisplay[$product->getId()] = $product;
         }
     }
     $this->helper->log('Recentlyviewed customer  : ' . $customerId . ', mode ' . $mode . ', limit : ' . $limit . ', items found : ' . count($productItems) . ', is customer logged in : ' . $isLoggedIn . ', products :' . count($productsToDisplay));
     $session->logout();
     return $productsToDisplay;
 }
Example #2
0
 /**
  * Create product duplicate
  *
  * @param \Magento\Catalog\Model\Product $product
  * @return \Magento\Catalog\Model\Product
  */
 public function copy(\Magento\Catalog\Model\Product $product)
 {
     $product->getWebsiteIds();
     $product->getCategoryIds();
     /** @var \Magento\Catalog\Model\Product $duplicate */
     $duplicate = $this->productFactory->create();
     $duplicate->setData($product->getData());
     $duplicate->setOptions([]);
     $duplicate->setIsDuplicate(true);
     $duplicate->setOriginalId($product->getEntityId());
     $duplicate->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);
     $duplicate->setCreatedAt(null);
     $duplicate->setUpdatedAt(null);
     $duplicate->setId(null);
     $duplicate->setStoreId(\Magento\Store\Model\Store::DEFAULT_STORE_ID);
     $this->copyConstructor->build($product, $duplicate);
     $isDuplicateSaved = false;
     do {
         $urlKey = $duplicate->getUrlKey();
         $urlKey = preg_match('/(.*)-(\\d+)$/', $urlKey, $matches) ? $matches[1] . '-' . ($matches[2] + 1) : $urlKey . '-1';
         $duplicate->setUrlKey($urlKey);
         try {
             $duplicate->save();
             $isDuplicateSaved = true;
         } catch (\Magento\Framework\Exception\AlreadyExistsException $e) {
         }
     } while (!$isDuplicateSaved);
     $this->getOptionRepository()->duplicate($product, $duplicate);
     $metadata = $this->getMetadataPool()->getMetadata(ProductInterface::class);
     $product->getResource()->duplicate($product->getData($metadata->getLinkField()), $duplicate->getData($metadata->getLinkField()));
     return $duplicate;
 }
Example #3
0
 /**
  * @return string
  */
 protected function _toHtml()
 {
     $storeId = $this->_getStoreId();
     $storeModel = $this->_storeManager->getStore($storeId);
     $newUrl = $this->_urlBuilder->getUrl('rss/catalog/new/store_id/' . $storeId);
     $title = __('New Products from %1', $storeModel->getFrontendName());
     $lang = $this->_scopeConfig->getValue('general/locale/code', \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $storeModel);
     /** @var $rssObj \Magento\Rss\Model\Rss */
     $rssObj = $this->_rssFactory->create();
     $rssObj->_addHeader(array('title' => $title, 'description' => $title, 'link' => $newUrl, 'charset' => 'UTF-8', 'language' => $lang));
     /** @var $product \Magento\Catalog\Model\Product */
     $product = $this->_productFactory->create();
     $todayStartOfDayDate = $this->_localeDate->date()->setTime('00:00:00')->toString(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT);
     $todayEndOfDayDate = $this->_localeDate->date()->setTime('23:59:59')->toString(\Magento\Framework\Stdlib\DateTime::DATETIME_INTERNAL_FORMAT);
     /** @var $products \Magento\Catalog\Model\Resource\Product\Collection */
     $products = $product->getCollection();
     $products->setStoreId($storeId);
     $products->addStoreFilter()->addAttributeToFilter('news_from_date', array('or' => array(0 => array('date' => true, 'to' => $todayEndOfDayDate), 1 => array('is' => new \Zend_Db_Expr('null')))), 'left')->addAttributeToFilter('news_to_date', array('or' => array(0 => array('date' => true, 'from' => $todayStartOfDayDate), 1 => array('is' => new \Zend_Db_Expr('null')))), 'left')->addAttributeToFilter(array(array('attribute' => 'news_from_date', 'is' => new \Zend_Db_Expr('not null')), array('attribute' => 'news_to_date', 'is' => new \Zend_Db_Expr('not null'))))->addAttributeToSort('news_from_date', 'desc')->addAttributeToSelect(array('name', 'short_description', 'description'), 'inner')->addAttributeToSelect(array('price', 'special_price', 'special_from_date', 'special_to_date', 'msrp_enabled', 'msrp_display_actual_price_type', 'msrp', 'thumbnail'), 'left')->applyFrontendPriceLimitations();
     $products->setVisibility($this->_visibility->getVisibleInCatalogIds());
     /*
     using resource iterator to load the data one by one
     instead of loading all at the same time. loading all data at the same time can cause the big memory allocation.
     */
     $this->_resourceIterator->walk($products->getSelect(), array(array($this, 'addNewItemXmlCallback')), array('rssObj' => $rssObj, 'product' => $product));
     return $rssObj->createRssXml();
 }
Example #4
0
 /**
  * Get categories tree as recursive array
  *
  * @param int $parentId
  * @param bool $asJson
  * @param int $recursionLevel
  * @return array
  */
 public function getTreeArray($parentId = null, $asJson = false, $recursionLevel = 3)
 {
     $productId = $this->_request->getParam('product');
     if ($productId) {
         $product = $this->_productFactory->create()->setId($productId);
         $this->_allowedCategoryIds = $product->getCategoryIds();
         unset($product);
     }
     $result = [];
     if ($parentId) {
         try {
             $category = $this->categoryRepository->get($parentId);
         } catch (NoSuchEntityException $e) {
             $category = null;
         }
         if ($category) {
             $tree = $this->_getNodesArray($this->getNode($category, $recursionLevel));
             if (!empty($tree) && !empty($tree['children'])) {
                 $result = $tree['children'];
             }
         }
     } else {
         $result = $this->_getNodesArray($this->getRoot(null, $recursionLevel));
     }
     if ($asJson) {
         return $this->_jsonEncoder->encode($result);
     }
     $this->_allowedCategoryIds = [];
     return $result;
 }
Example #5
0
 /**
  * Build product based on user request
  *
  * @param RequestInterface $request
  * @return \Magento\Catalog\Model\Product
  */
 public function build(RequestInterface $request)
 {
     $productId = (int) $request->getParam('id');
     /** @var $product \Magento\Catalog\Model\Product */
     $product = $this->productFactory->create();
     $product->setStoreId($request->getParam('store', 0));
     $typeId = $request->getParam('type');
     if (!$productId && $typeId) {
         $product->setTypeId($typeId);
     }
     $product->setData('_edit_mode', true);
     if ($productId) {
         try {
             $product->load($productId);
         } catch (\Exception $e) {
             $product->setTypeId(\Magento\Catalog\Model\Product\Type::DEFAULT_TYPE);
             $this->logger->critical($e);
         }
     }
     $setId = (int) $request->getParam('set');
     if ($setId) {
         $product->setAttributeSetId($setId);
     }
     $this->registry->register('product', $product);
     $this->registry->register('current_product', $product);
     $this->wysiwygConfig->setStoreId($request->getParam('store'));
     return $product;
 }
Example #6
0
 /**
  * Product variations attributes validation
  *
  * @param Product $parentProduct
  * @param array $products
  * @param RequestInterface $request
  * @return array
  */
 protected function _validateProductVariations(Product $parentProduct, array $products, RequestInterface $request)
 {
     $this->eventManager->dispatch('catalog_product_validate_variations_before', ['product' => $parentProduct, 'variations' => $products]);
     $validationResult = [];
     foreach ($products as $productData) {
         $product = $this->productFactory->create();
         $product->setData('_edit_mode', true);
         $storeId = $request->getParam('store');
         if ($storeId) {
             $product->setStoreId($storeId);
         }
         $product->setAttributeSetId($parentProduct->getAttributeSetId());
         $product->addData($this->getRequiredDataFromProduct($parentProduct));
         $product->addData($productData);
         $product->setCollectExceptionMessages(true);
         $configurableAttribute = [];
         $encodedData = $productData['configurable_attribute'];
         if ($encodedData) {
             $configurableAttribute = $this->jsonHelper->jsonDecode($encodedData);
         }
         $configurableAttribute = implode('-', $configurableAttribute);
         $errorAttributes = $product->validate();
         if (is_array($errorAttributes)) {
             foreach ($errorAttributes as $attributeCode => $result) {
                 if (is_string($result)) {
                     $key = 'variations-matrix-' . $configurableAttribute . '-' . $attributeCode;
                     $validationResult[$key] = $result;
                 }
             }
         }
     }
     return $validationResult;
 }
Example #7
0
 /**
  * Get associated grouped products grid popup
  *
  * @return \Magento\Framework\View\Result\Layout
  */
 public function execute()
 {
     $productId = (int) $this->getRequest()->getParam('id');
     /** @var $product \Magento\Catalog\Model\Product */
     $product = $this->factory->create();
     $product->setStoreId($this->getRequest()->getParam('store', 0));
     $typeId = $this->getRequest()->getParam('type');
     if (!$productId && $typeId) {
         $product->setTypeId($typeId);
     }
     $product->setData('_edit_mode', true);
     if ($productId) {
         try {
             $product->load($productId);
         } catch (\Exception $e) {
             $product->setTypeId(\Magento\Catalog\Model\Product\Type::DEFAULT_TYPE);
             $this->logger->critical($e);
         }
     }
     $setId = (int) $this->getRequest()->getParam('set');
     if ($setId) {
         $product->setAttributeSetId($setId);
     }
     $this->registry->register('current_product', $product);
     /** @var \Magento\Framework\View\Result\Layout $resultLayout */
     $resultLayout = $this->resultFactory->create(ResultFactory::TYPE_LAYOUT);
     return $resultLayout;
 }
Example #8
0
 /**
  * {@inheritdoc}
  */
 public function run()
 {
     $this->logger->log('Installing product links:');
     $entityFileAssociation = ['related', 'upsell', 'crosssell'];
     foreach ($this->postInstaller->getInstalledModuleList() as $moduleName) {
         foreach ($entityFileAssociation as $linkType) {
             $fileName = substr($moduleName, strpos($moduleName, "_") + 1) . '/Links/' . $linkType . '.csv';
             $fileName = $this->fixtureHelper->getPath($fileName);
             if (!$fileName) {
                 continue;
             }
             /** @var \Magento\SampleData\Helper\Csv\ReaderFactory $csvReader */
             $csvReader = $this->csvReaderFactory->create(['fileName' => $fileName, 'mode' => 'r']);
             foreach ($csvReader as $row) {
                 /** @var \Magento\Catalog\Model\Product $product */
                 $product = $this->productFactory->create();
                 $productId = $product->getIdBySku($row['sku']);
                 if (!$productId) {
                     continue;
                 }
                 $product->setId($productId);
                 $links = [$linkType => []];
                 foreach (explode("\n", $row['linked_sku']) as $linkedProductSku) {
                     $linkedProductId = $product->getIdBySku($linkedProductSku);
                     if ($linkedProductId) {
                         $links[$linkType][$linkedProductId] = [];
                     }
                 }
                 $this->linksInitializer->initializeLinks($product, $links);
                 $product->getLinkInstance()->saveProductRelations($product);
                 $this->logger->logInline('.');
             }
         }
     }
 }
Example #9
0
 /**
  * Get or create new instance of product
  *
  * @return \Magento\Catalog\Model\Product
  */
 private function _getProduct()
 {
     if (!$this->hasData('product')) {
         $this->setProduct($this->_productFactory->create());
     }
     return $this->getProduct();
 }
Example #10
0
 /**
  * Create product duplicate
  *
  * @param \Magento\Catalog\Model\Product $product
  * @return \Magento\Catalog\Model\Product
  */
 public function copy(\Magento\Catalog\Model\Product $product)
 {
     $product->getWebsiteIds();
     $product->getCategoryIds();
     $duplicate = $this->productFactory->create();
     $duplicate->setData($product->getData());
     $duplicate->setIsDuplicate(true);
     $duplicate->setOriginalId($product->getId());
     $duplicate->setStatus(\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_DISABLED);
     $duplicate->setCreatedAt(null);
     $duplicate->setUpdatedAt(null);
     $duplicate->setId(null);
     $duplicate->setStoreId(\Magento\Store\Model\Store::DEFAULT_STORE_ID);
     $this->copyConstructor->build($product, $duplicate);
     $isDuplicateSaved = false;
     do {
         $urlKey = $duplicate->getUrlKey();
         $urlKey = preg_match('/(.*)-(\\d+)$/', $urlKey, $matches) ? $matches[1] . '-' . ($matches[2] + 1) : $urlKey . '-1';
         $duplicate->setUrlKey($urlKey);
         try {
             $duplicate->save();
             $isDuplicateSaved = true;
         } catch (DuplicateEntryException $e) {
         }
     } while (!$isDuplicateSaved);
     $product->getOptionInstance()->duplicate($product->getId(), $duplicate->getId());
     $product->getResource()->duplicate($product->getId(), $duplicate->getId());
     return $duplicate;
 }
 /**
  * Populate product with variation of attributes
  *
  * @param \Magento\Catalog\Api\Data\ProductInterface $product
  * @param array $attributes
  * @return \Magento\Catalog\Api\Data\ProductInterface[]
  */
 public function create(\Magento\Catalog\Api\Data\ProductInterface $product, $attributes)
 {
     $variations = $this->variationMatrix->getVariations($attributes);
     $products = [];
     foreach ($variations as $variation) {
         $price = $product->getPrice();
         /** @var \Magento\Catalog\Model\Product $item */
         $item = $this->productFactory->create();
         $item->setData($product->getData());
         $suffix = '';
         foreach ($variation as $attributeId => $valueInfo) {
             $suffix .= '-' . $valueInfo['value'];
             $customAttribute = $this->customAttributeFactory->create()->setAttributeCode($attributes[$attributeId]['attribute_code'])->setValue($valueInfo['value']);
             $customAttributes = array_merge($item->getCustomAttributes(), [$attributes[$attributeId]['attribute_code'] => $customAttribute]);
             $item->setData('custom_attributes', $customAttributes);
             $priceInfo = $valueInfo['price'];
             $price += (!empty($priceInfo['is_percent']) ? $product->getPrice() / 100.0 : 1.0) * $priceInfo['pricing_value'];
         }
         $item->setPrice($price);
         $item->setName($product->getName() . $suffix);
         $item->setSku($product->getSku() . $suffix);
         $item->setVisibility(\Magento\Catalog\Model\Product\Visibility::VISIBILITY_NOT_VISIBLE);
         $products[] = $item;
     }
     return $products;
 }
Example #12
0
 /**
  * Get associated grouped products grid popup
  *
  * @return void
  */
 public function execute()
 {
     $productId = (int) $this->getRequest()->getParam('id');
     /** @var $product \Magento\Catalog\Model\Product */
     $product = $this->factory->create();
     $product->setStoreId($this->getRequest()->getParam('store', 0));
     $typeId = $this->getRequest()->getParam('type');
     if (!$productId && $typeId) {
         $product->setTypeId($typeId);
     }
     $product->setData('_edit_mode', true);
     if ($productId) {
         try {
             $product->load($productId);
         } catch (\Exception $e) {
             $product->setTypeId(\Magento\Catalog\Model\Product\Type::DEFAULT_TYPE);
             $this->logger->logException($e);
         }
     }
     $setId = (int) $this->getRequest()->getParam('set');
     if ($setId) {
         $product->setAttributeSetId($setId);
     }
     $this->registry->register('current_product', $product);
     $this->_view->loadLayout(false);
     $this->_view->renderLayout();
 }
Example #13
0
 /**
  * @return array
  */
 public function getMediaAttributes()
 {
     static $simple;
     if (empty($simple)) {
         $simple = $this->productFactory->create()->setTypeId(Type::TYPE_SIMPLE)->getMediaAttributes();
     }
     return $simple;
 }
Example #14
0
 /**
  * @param int $storeId
  * @param int $customerGroupId
  * @return \Magento\Catalog\Model\ResourceModel\Product\Collection
  */
 public function getProductsCollection($storeId, $customerGroupId)
 {
     $websiteId = $this->storeManager->getStore($storeId)->getWebsiteId();
     /** @var $product \Magento\Catalog\Model\Product */
     $product = $this->productFactory->create();
     $product->setStoreId($storeId);
     $collection = $product->getResourceCollection()->addPriceDataFieldFilter('%s < %s', ['final_price', 'price'])->addPriceData($customerGroupId, $websiteId)->addAttributeToSelect(['name', 'short_description', 'description', 'price', 'thumbnail', 'special_price', 'special_to_date', 'msrp_display_actual_price_type', 'msrp'], 'left')->addAttributeToSort('name', 'asc');
     return $collection;
 }
Example #15
0
 /**
  * Get product id
  *
  * @param \Magento\Sales\Model\Order\Admin\Item $subject
  * @param callable $proceed
  * @param \Magento\Sales\Model\Order\Item $item
  *
  * @return int
  * @SuppressWarnings(PHPMD.UnusedFormalParameter)
  */
 public function aroundGetProductId(\Magento\Sales\Model\Order\Admin\Item $subject, \Closure $proceed, \Magento\Sales\Model\Order\Item $item)
 {
     if ($item->getProductType() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE) {
         $productOptions = $item->getProductOptions();
         $product = $this->productFactory->create();
         return $product->getIdBySku($productOptions['simple_sku']);
     }
     return $proceed($item);
 }
 /**
  * Get the products to display for table.
  *
  * @return $this
  */
 public function getLoadedProductCollection()
 {
     $mode = $this->getRequest()->getActionName();
     $limit = $this->recommnededHelper->getDisplayLimitByMode($mode);
     $productIds = $this->recommnededHelper->getProductPushIds();
     $productCollection = $this->productFactory->create()->getCollection()->addAttributeToSelect('*')->addAttributeToFilter('entity_id', ['in' => $productIds]);
     $productCollection->getSelect()->limit($limit);
     //important check the salable product in template
     return $productCollection;
 }
Example #17
0
 /**
  * Apply sorting and filtering to collection
  *
  * @return $this
  */
 protected function _prepareCollection()
 {
     $collection = $this->_productFactory->create()->getCollection()->setOrder('id')->addAttributeToSelect('name')->addAttributeToSelect('sku')->addAttributeToSelect('price')->addAttributeToSelect('attribute_set_id')->addAttributeToFilter('entity_id', ['nin' => $this->_getSelectedProducts()])->addAttributeToFilter('type_id', ['in' => $this->getAllowedSelectionTypes()])->addFilterByRequiredOptions()->addStoreFilter(\Magento\Store\Model\Store::DEFAULT_STORE_ID);
     if ($this->getFirstShow()) {
         $collection->addIdFilter('-1');
         $this->setEmptyText(__('Please enter search conditions to view products.'));
     }
     $this->setCollection($collection);
     return parent::_prepareCollection();
 }
Example #18
0
 /**
  * Load product by SKU
  *
  * @param  string $productSku
  * @return \Magento\Catalog\Model\Product
  * @throws NoSuchEntityException
  */
 public function load($productSku)
 {
     /** @var \Magento\Catalog\Model\Product $product */
     $product = $this->productFactory->create();
     $productId = $product->getIdBySku($productSku);
     if (!$productId) {
         throw new NoSuchEntityException('There is no product with provided SKU');
     }
     $product->load($productId);
     return $product;
 }
Example #19
0
 /**
  * @return void
  */
 protected function _construct()
 {
     $this->_blockGroup = 'Magento_Reports';
     $this->_controller = 'adminhtml_review_detail';
     $product = $this->_productFactory->create()->load($this->getRequest()->getParam('id'));
     $this->_headerText = __('Reviews for %1', $product->getName());
     parent::_construct();
     $this->buttonList->remove('add');
     $this->setBackUrl($this->getUrl('reports/report_review/product/'));
     $this->_addBackButton();
 }
Example #20
0
 /**
  * Validate Product Rule Condition
  *
  * @param \Magento\Framework\Object $object
  * @return bool
  */
 public function validate(\Magento\Framework\Object $object)
 {
     //@todo reimplement this method when is fixed MAGETWO-5713
     /** @var \Magento\Catalog\Model\Product $product */
     $product = $object->getProduct();
     if (!$product instanceof \Magento\Catalog\Model\Product) {
         $product = $this->_productFactory->create()->load($object->getProductId());
     }
     $product->setQuoteItemQty($object->getQty())->setQuoteItemPrice($object->getPrice())->setQuoteItemRowTotal($object->getBaseRowTotal());
     return parent::validate($product);
 }
Example #21
0
 /**
  * Generate url rewrites for products assigned to website
  *
  * @param int $websiteId
  * @param int $originWebsiteId
  * @return array
  */
 protected function generateProductUrls($websiteId, $originWebsiteId)
 {
     $urls = [];
     $websiteIds = $websiteId != $originWebsiteId ? [$websiteId, $originWebsiteId] : [$websiteId];
     $collection = $this->productFactory->create()->getCollection()->addCategoryIds()->addAttributeToSelect(['name', 'url_path', 'url_key'])->addWebsiteFilter($websiteIds);
     foreach ($collection as $product) {
         /** @var \Magento\Catalog\Model\Product $product */
         $product->setStoreId(Store::DEFAULT_STORE_ID);
         $urls = array_merge($urls, $this->productUrlRewriteGenerator->generate($product));
     }
     return $urls;
 }
Example #22
0
 /**
  * @return array
  */
 public function getOldSkus()
 {
     if (!$this->oldSkus) {
         $columns = ['entity_id', 'type_id', 'attribute_set_id', 'sku'];
         foreach ($this->productFactory->create()->getProductEntitiesInfo($columns) as $info) {
             $typeId = $info['type_id'];
             $sku = $info['sku'];
             $this->oldSkus[$sku] = ['type_id' => $typeId, 'attr_set_id' => $info['attribute_set_id'], 'entity_id' => $info['entity_id'], 'supported_type' => isset($this->productTypeModels[$typeId])];
         }
     }
     return $this->oldSkus;
 }
Example #23
0
 /**
  * @param int $storeId
  * @return \Magento\Catalog\Model\ResourceModel\Product\Collection
  */
 public function getProductsCollection($storeId)
 {
     /** @var $product \Magento\Catalog\Model\Product */
     $product = $this->productFactory->create();
     $todayStartOfDayDate = $this->localeDate->date()->setTime(0, 0)->format('Y-m-d H:i:s');
     $todayEndOfDayDate = $this->localeDate->date()->setTime(23, 59, 59)->format('Y-m-d H:i:s');
     /** @var $products \Magento\Catalog\Model\ResourceModel\Product\Collection */
     $products = $product->getResourceCollection();
     $products->setStoreId($storeId);
     $products->addStoreFilter()->addAttributeToFilter('news_from_date', ['or' => [0 => ['date' => true, 'to' => $todayEndOfDayDate], 1 => ['is' => new \Zend_Db_Expr('null')]]], 'left')->addAttributeToFilter('news_to_date', ['or' => [0 => ['date' => true, 'from' => $todayStartOfDayDate], 1 => ['is' => new \Zend_Db_Expr('null')]]], 'left')->addAttributeToFilter([['attribute' => 'news_from_date', 'is' => new \Zend_Db_Expr('not null')], ['attribute' => 'news_to_date', 'is' => new \Zend_Db_Expr('not null')]])->addAttributeToSort('news_from_date', 'desc')->addAttributeToSelect(['name', 'short_description', 'description'], 'inner')->addAttributeToSelect(['price', 'special_price', 'special_from_date', 'special_to_date', 'msrp_display_actual_price_type', 'msrp', 'thumbnail'], 'left')->applyFrontendPriceLimitations();
     $products->setVisibility($this->visibility->getVisibleInCatalogIds());
     return $products;
 }
 /**
  * @return \Magento\Catalog\Model\ResourceModel\Product\Collection
  */
 public function getProductsCollection()
 {
     /* @var $product \Magento\Catalog\Model\Product */
     $product = $this->productFactory->create();
     /* @var $collection \Magento\Catalog\Model\ResourceModel\Product\Collection */
     $collection = $product->getCollection();
     /** @var $resourceStock \Magento\CatalogInventory\Model\ResourceModel\Stock */
     $resourceStock = $this->stockFactory->create();
     $resourceStock->addLowStockFilter($collection, ['qty', 'notify_stock_qty', 'low_stock_date', 'use_config' => 'use_config_notify_stock_qty']);
     $collection->addAttributeToSelect('name', true)->addAttributeToFilter('status', ['in' => $this->productStatus->getVisibleStatusIds()])->setOrder('low_stock_date');
     $this->eventManager->dispatch('rss_catalog_notify_stock_collection_select', ['collection' => $collection]);
     return $collection;
 }
Example #25
0
 public function execute()
 {
     $params = $this->getRequest()->getParams();
     /** @var \Magento\Checkout\Model\Cart $cart */
     $cart = $this->cartFactory->create();
     $successMessage = '';
     $websiteId = $this->storeManager->getStore()->getWebsiteId();
     foreach ($params as $key => $product) {
         if ($product && is_array($product)) {
             $productModel = $this->productFactory->create();
             // loadByAttribute() return false if the product was not found. There is no need to check the ID,
             // but lets stay on the safe side for the future Magento releases
             /** @var \Magento\Catalog\Model\Product $productBySKU */
             $productBySKU = $productModel->loadByAttribute('sku', $product['sku']);
             if (!$productBySKU || !($productId = $productBySKU->getId())) {
                 continue;
             }
             $stockItem = $this->stockItemApiFactory->create();
             /** @var \Magento\CatalogInventory\Model\ResourceModel\Stock\Item $stockItemResource */
             $stockItemResource = $this->stockItemApiResourceFactory->create();
             $stockItemResource->loadByProductId($stockItem, $productId, $websiteId);
             $qty = $stockItem->getQty();
             try {
                 if (!$cart->getQuote()->hasProductId($productId) && is_numeric($product['qty']) && $qty > $product['qty']) {
                     $cart->addProduct($productBySKU, (int) $product['qty']);
                     $successMessage .= __('%1 was added to your shopping cart.' . '</br>', $this->escaper->escapeHtml($productBySKU->getName()));
                 }
                 unset($params[$key]);
             } catch (\Exception $e) {
                 $this->rejoinerHelper->log($e->getMessage());
             }
         }
     }
     if (isset($params['coupon_code'])) {
         $cart->getQuote()->setCouponCode($params['coupon_code'])->collectTotals();
     }
     try {
         $cart->getQuote()->save();
         $cart->save();
     } catch (\Exception $e) {
         $this->rejoinerHelper->log($e->getMessage());
     }
     $this->checkoutSession->setCartWasUpdated(true);
     if ($successMessage) {
         $this->messageManager->addSuccess($successMessage);
     }
     $url = $this->_url->getUrl('checkout/cart/', ['updateCart' => true]);
     $this->getResponse()->setRedirect($url);
 }
Example #26
0
 /**
  * @return ModelProduct
  */
 public function getProduct()
 {
     if (!$this->getData('product') instanceof ModelProduct) {
         if ($this->getData('product')->getProductId()) {
             $productId = $this->getData('product')->getProductId();
         }
         if ($productId) {
             $product = $this->_productFactory->create()->load($productId);
             if ($product) {
                 $this->setProduct($product);
             }
         }
     }
     return $this->getData('product');
 }
Example #27
0
 /**
  * @param  Product $product
  * @param  \Magento\Catalog\Model\Product $productModel
  * @return \Magento\Catalog\Model\Product
  * @throws \RuntimeException
  */
 public function toModel(Product $product, \Magento\Catalog\Model\Product $productModel = null)
 {
     /** @var \Magento\Catalog\Model\Product $productModel */
     $productModel = $productModel ?: $this->productFactory->create();
     $productModel->addData(ExtensibleDataObjectConverter::toFlatArray($product));
     if (!is_numeric($productModel->getAttributeSetId())) {
         $productModel->setAttributeSetId($productModel->getDefaultAttributeSetId());
     }
     if (!$productModel->hasTypeId()) {
         $productModel->setTypeId(\Magento\Catalog\Model\Product\Type::DEFAULT_TYPE);
     } elseif (!isset($this->productTypes->getTypes()[$productModel->getTypeId()])) {
         throw new \RuntimeException('Illegal product type');
     }
     return $productModel;
 }
Example #28
0
 /**
  * Prepare form
  *
  * @return null|void
  * @SuppressWarnings(PHPMD.CyclomaticComplexity)
  * @SuppressWarnings(PHPMD.ExcessiveMethodLength)
  */
 protected function _prepareForm()
 {
     /** @var \Magento\Framework\Data\Form $form */
     $form = $this->_formFactory->create();
     $form->setFieldNameSuffix('simple_product');
     $form->setDataObject($this->getProduct());
     $fieldset = $form->addFieldset('simple_product', array('legend' => __('Quick simple product creation')));
     $this->_addElementTypes($fieldset);
     $attributesConfig = array('autogenerate' => array('name', 'sku'), 'additional' => array('name', 'sku', 'visibility', 'status'));
     $availableTypes = array('text', 'select', 'multiselect', 'textarea', 'price', 'weight');
     $attributes = $this->_productFactory->create()->setTypeId(\Magento\Catalog\Model\Product\Type::TYPE_SIMPLE)->setAttributeSetId($this->getProduct()->getAttributeSetId())->getAttributes();
     /* Standard attributes */
     foreach ($attributes as $attribute) {
         if ($attribute->getIsRequired() && $attribute->getApplyTo() && !in_array(\Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE, $attribute->getApplyTo()) && !in_array($attribute->getId(), $this->getProduct()->getTypeInstance()->getUsedProductAttributeIds($this->getProduct())) || in_array($attribute->getAttributeCode(), $attributesConfig['additional'])) {
             $inputType = $attribute->getFrontend()->getInputType();
             if (!in_array($inputType, $availableTypes)) {
                 continue;
             }
             $attributeCode = $attribute->getAttributeCode();
             $attribute->setAttributeCode('simple_product_' . $attributeCode);
             $element = $fieldset->addField('simple_product_' . $attributeCode, $inputType, array('label' => $attribute->getFrontend()->getLabel(), 'name' => $attributeCode, 'required' => $attribute->getIsRequired()))->setEntityAttribute($attribute);
             if (in_array($attributeCode, $attributesConfig['autogenerate'])) {
                 $element->setDisabled('true');
                 $element->setValue($this->getProduct()->getData($attributeCode));
                 $element->setAfterElementHtml('<input type="checkbox" id="simple_product_' . $attributeCode . '_autogenerate" ' . 'name="simple_product[' . $attributeCode . '_autogenerate]" value="1" ' . 'onclick="toggleValueElements(this, this.parentNode)" checked="checked" /> ' . '<label for="simple_product_' . $attributeCode . '_autogenerate" >' . __('Autogenerate') . '</label>');
             }
             if ($inputType == 'select' || $inputType == 'multiselect') {
                 $element->setValues($attribute->getFrontend()->getSelectOptions());
             }
         }
     }
     /* Configurable attributes */
     $usedAttributes = $this->getProduct()->getTypeInstance()->getUsedProductAttributes($this->getProduct());
     foreach ($usedAttributes as $attribute) {
         $attributeCode = $attribute->getAttributeCode();
         $fieldset->addField('simple_product_' . $attributeCode, 'select', array('label' => $attribute->getFrontend()->getLabel(), 'name' => $attributeCode, 'values' => $attribute->getSource()->getAllOptions(true, true), 'required' => true, 'class' => 'validate-configurable', 'onchange' => 'superProduct.showPricing(this, \'' . $attributeCode . '\')'));
         $fieldset->addField('simple_product_' . $attributeCode . '_pricing_value', 'hidden', array('name' => 'pricing[' . $attributeCode . '][value]'));
         $fieldset->addField('simple_product_' . $attributeCode . '_pricing_type', 'hidden', array('name' => 'pricing[' . $attributeCode . '][is_percent]'));
     }
     /* Inventory Data */
     $fieldset->addField('simple_product_inventory_qty', 'text', array('label' => __('Qty'), 'name' => 'stock_data[qty]', 'class' => 'validate-number', 'required' => true, 'value' => 0));
     $fieldset->addField('simple_product_inventory_is_in_stock', 'select', array('label' => __('Stock Availability'), 'name' => 'stock_data[is_in_stock]', 'values' => array(array('value' => 1, 'label' => __('In Stock')), array('value' => 0, 'label' => __('Out of Stock'))), 'value' => 1));
     $stockHiddenFields = array('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, 'is_qty_decimal' => 0);
     foreach ($stockHiddenFields as $fieldName => $fieldValue) {
         $fieldset->addField('simple_product_inventory_' . $fieldName, 'hidden', array('name' => 'stock_data[' . $fieldName . ']', 'value' => $fieldValue));
     }
     $this->setForm($form);
 }
Example #29
0
 /**
  * @return $this
  */
 protected function _prepareColumns()
 {
     $this->addColumn('entity_id', array('header' => __('ID'), 'type' => 'number', 'index' => 'entity_id', 'header_css_class' => 'col-id', 'column_css_class' => 'col-id'));
     $this->addColumn('name', array('header' => __('Name'), 'index' => 'name', 'class' => 'xxx'));
     $store = $this->_getStore();
     if ($store->getId()) {
         $this->addColumn('custom_name', array('header' => __('Name in %1', $store->getName()), 'index' => 'custom_name', 'header_css_class' => 'col-name', 'column_css_class' => 'col-name'));
     }
     $this->addColumn('type', array('header' => __('Type'), 'index' => 'type_id', 'type' => 'options', 'options' => $this->_type->getOptionArray()));
     $sets = $this->_setsFactory->create()->setEntityTypeFilter($this->_productFactory->create()->getResource()->getTypeId())->load()->toOptionHash();
     $this->addColumn('set_name', array('header' => __('Attribute Set'), 'index' => 'attribute_set_id', 'type' => 'options', 'options' => $sets, 'header_css_class' => 'col-attr-name', 'column_css_class' => 'col-attr-name'));
     $this->addColumn('sku', array('header' => __('SKU'), 'index' => 'sku'));
     $store = $this->_getStore();
     $this->addColumn('price', array('header' => __('Price'), 'type' => 'price', 'currency_code' => $store->getBaseCurrency()->getCode(), 'index' => 'price', 'header_css_class' => 'col-price', 'column_css_class' => 'col-price'));
     if ($this->_catalogData->isModuleEnabled('Magento_CatalogInventory')) {
         $this->addColumn('qty', array('header' => __('Quantity'), 'type' => 'number', 'index' => 'qty'));
     }
     $this->addColumn('visibility', array('header' => __('Visibility'), 'index' => 'visibility', 'type' => 'options', 'options' => $this->_visibility->getOptionArray(), 'header_css_class' => 'col-visibility', 'column_css_class' => 'col-visibility'));
     $this->addColumn('status', array('header' => __('Status'), 'index' => 'status', 'type' => 'options', 'options' => $this->_status->getOptionArray()));
     if (!$this->_storeManager->isSingleStoreMode()) {
         $this->addColumn('websites', array('header' => __('Websites'), 'sortable' => false, 'index' => 'websites', 'type' => 'options', 'options' => $this->_websiteFactory->create()->getCollection()->toOptionHash(), 'header_css_class' => 'col-websites', 'column_css_class' => 'col-websites'));
     }
     $this->addColumn('edit', array('header' => __('Edit'), 'type' => 'action', 'getter' => 'getId', 'actions' => array(array('caption' => __('Edit'), 'url' => array('base' => '*/*/edit', 'params' => array('store' => $this->getRequest()->getParam('store'))), 'field' => 'id')), 'filter' => false, 'sortable' => false, 'index' => 'stores', 'header_css_class' => 'col-action', 'column_css_class' => 'col-action'));
     if ($this->_catalogData->isModuleEnabled('Magento_Rss')) {
         $this->addRssList('rss/catalog/notifystock', __('Notify Low Stock RSS'));
     }
     return parent::_prepareColumns();
 }
 /**
  * @param string $optionType
  *
  * @magentoApiDataFixture Magento/Catalog/_files/product_with_options.php
  * @magentoAppIsolation enabled
  * @dataProvider validOptionDataProvider
  * @SuppressWarnings(PHPMD.UnusedLocalVariable)
  */
 public function testUpdateOptionAddingNewValue($optionType)
 {
     $productId = 1;
     $fixtureOption = null;
     $valueData = ['price' => 100500, 'price_type' => 'fixed', 'sku' => 'new option sku ' . $optionType, 'title' => 'New Option Title', 'sort_order' => 100];
     $product = $this->productFactory->create();
     $product->load($productId);
     /**@var $option \Magento\Catalog\Model\Product\Option */
     foreach ($product->getOptions() as $option) {
         if ($option->getType() == $optionType) {
             $fixtureOption = $option;
             break;
         }
     }
     $values = [];
     foreach ($option->getValues() as $key => $value) {
         $values[] = ['price' => $value->getPrice(), 'price_type' => $value->getPriceType(), 'sku' => $value->getSku(), 'title' => $value->getTitle(), 'sort_order' => $value->getSortOrder()];
     }
     $values[] = $valueData;
     $data = ['product_sku' => $option->getProductSku(), 'title' => $option->getTitle(), 'type' => $option->getType(), 'is_require' => $option->getIsRequire(), 'sort_order' => $option->getSortOrder(), 'values' => $values];
     $serviceInfo = ['rest' => ['resourcePath' => '/V1/products/options/' . $fixtureOption->getId(), 'httpMethod' => \Magento\Framework\Webapi\Rest\Request::HTTP_METHOD_PUT], 'soap' => ['service' => self::SERVICE_NAME, 'serviceVersion' => 'V1', 'operation' => self::SERVICE_NAME . 'Save']];
     if (TESTS_WEB_API_ADAPTER == self::ADAPTER_SOAP) {
         $data['option_id'] = $fixtureOption->getId();
         $valueObject = $this->_webApiCall($serviceInfo, ['option_id' => $fixtureOption->getId(), 'option' => $data]);
     } else {
         $valueObject = $this->_webApiCall($serviceInfo, ['option' => $data]);
     }
     $values = end($valueObject['values']);
     $this->assertEquals($valueData['price'], $values['price']);
     $this->assertEquals($valueData['price_type'], $values['price_type']);
     $this->assertEquals($valueData['sku'], $values['sku']);
     $this->assertEquals('New Option Title', $values['title']);
     $this->assertEquals(100, $values['sort_order']);
 }