Example #1
0
 /**
  * Process stock emails
  *
  * @param \Magento\ProductAlert\Model\Email $email
  * @return $this
  */
 protected function _processStock(\Magento\ProductAlert\Model\Email $email)
 {
     $email->setType('stock');
     foreach ($this->_getWebsites() as $website) {
         /* @var $website \Magento\Store\Model\Website */
         if (!$website->getDefaultGroup() || !$website->getDefaultGroup()->getDefaultStore()) {
             continue;
         }
         if (!$this->_scopeConfig->getValue(self::XML_PATH_STOCK_ALLOW, \Magento\Store\Model\ScopeInterface::SCOPE_STORE, $website->getDefaultGroup()->getDefaultStore()->getId())) {
             continue;
         }
         try {
             $collection = $this->_stockColFactory->create()->addWebsiteFilter($website->getId())->addStatusFilter(0)->setCustomerOrder();
         } catch (\Exception $e) {
             $this->_errors[] = $e->getMessage();
             return $this;
         }
         $previousCustomer = null;
         $email->setWebsite($website);
         foreach ($collection as $alert) {
             try {
                 if (!$previousCustomer || $previousCustomer->getId() != $alert->getCustomerId()) {
                     $customer = $this->_customerAccountService->getCustomer($alert->getCustomerId());
                     if ($previousCustomer) {
                         $email->send();
                     }
                     if (!$customer) {
                         continue;
                     }
                     $previousCustomer = $customer;
                     $email->clean();
                     $email->setCustomerData($customer);
                 } else {
                     $customer = $previousCustomer;
                 }
                 $product = $this->_productFactory->create()->setStoreId($website->getDefaultStore()->getId())->load($alert->getProductId());
                 /* @var $product \Magento\Catalog\Model\Product */
                 if (!$product) {
                     continue;
                 }
                 $product->setCustomerGroupId($customer->getGroupId());
                 if ($product->isSalable()) {
                     $email->addStockProduct($product);
                     $alert->setSendDate($this->_dateFactory->create()->gmtDate());
                     $alert->setSendCount($alert->getSendCount() + 1);
                     $alert->setStatus(1);
                     $alert->save();
                 }
             } catch (\Exception $e) {
                 $this->_errors[] = $e->getMessage();
             }
         }
         if ($previousCustomer) {
             try {
                 $email->send();
             } catch (\Exception $e) {
                 $this->_errors[] = $e->getMessage();
             }
         }
     }
     return $this;
 }