couponGenerator = $couponGenerator ?: $this->_objectManager->get(CouponGenerator::class); } /** * Generate Coupons action * * @return void */ public function execute() { if (!$this->getRequest()->isAjax()) { $this->_forward('noroute'); return; } $result = []; $this->_initRule(); $rule = $this->_coreRegistry->registry(\Magento\SalesRule\Model\RegistryConstants::CURRENT_SALES_RULE); if (!$rule->getId()) { $result['error'] = __('Rule is not defined'); } else { try { $data = $this->getRequest()->getParams(); if (!empty($data['to_date'])) { $inputFilter = new \Zend_Filter_Input(['to_date' => $this->_dateFilter], [], $data); $data = $inputFilter->getUnescaped(); } $couponCodes = $this->couponGenerator->generateCodes($data); $generated = count($couponCodes); $this->messageManager->addSuccessMessage(__('%1 coupon(s) have been generated.', $generated)); $this->_view->getLayout()->initMessages(); $result['messages'] = $this->_view->getLayout()->getMessagesBlock()->getGroupedHtml(); } catch (\Magento\Framework\Exception\InputException $inputException) { $result['error'] = __('Invalid data provided'); } catch (\Magento\Framework\Exception\LocalizedException $e) { $result['error'] = $e->getMessage(); } catch (\Exception $e) { $result['error'] = __( 'Something went wrong while generating coupons. Please review the log and try again.' ); $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e); } } $this->getResponse()->representJson( $this->_objectManager->get(\Magento\Framework\Json\Helper\Data::class)->jsonEncode($result) ); } }