/** * Save coupon. * * @param \Magento\SalesRule\Api\Data\CouponInterface $coupon * @return \Magento\SalesRule\Api\Data\CouponInterface * @throws \Magento\Framework\Exception\InputException If there is a problem with the input * @throws \Magento\Framework\Exception\NoSuchEntityException If a coupon ID is sent but the coupon does not exist * @throws \Magento\Framework\Exception\LocalizedException */ public function save(\Magento\SalesRule\Api\Data\CouponInterface $coupon) { //if coupon id is provided, use the existing coupon and blend in the new data supplied $couponId = $coupon->getCouponId(); if ($couponId) { $existingCoupon = $this->getById($couponId); $mergedData = array_merge($existingCoupon->getData(), $coupon->getData()); $coupon->setData($mergedData); } //blend in specific fields from the rule try { $rule = $this->ruleFactory->create()->load($coupon->getRuleId()); if (!$rule->getRuleId()) { throw \Magento\Framework\Exception\NoSuchEntityException::singleField('rule_id', $coupon->getRuleId()); } if ($rule->getCouponType() == $rule::COUPON_TYPE_NO_COUPON) { throw new \Magento\Framework\Exception\LocalizedException(__('Specified rule does not allow coupons')); } elseif ($rule->getUseAutoGeneration() && $coupon->getType() == $coupon::TYPE_MANUAL) { throw new \Magento\Framework\Exception\LocalizedException(__('Specified rule only allows auto generated coupons')); } elseif (!$rule->getUseAutoGeneration() && $coupon->getType() == $coupon::TYPE_GENERATED) { throw new \Magento\Framework\Exception\LocalizedException(__('Specified rule does not allow auto generated coupons')); } $coupon->setExpirationDate($rule->getToDate()); $coupon->setUsageLimit($rule->getUsesPerCoupon()); $coupon->setUsagePerCustomer($rule->getUsesPerCustomer()); } catch (\Exception $e) { throw new \Magento\Framework\Exception\LocalizedException(__('Error occurred when saving coupon: %1', $e->getMessage())); } $this->resourceModel->save($coupon); return $coupon; }
public function testGetMetadataValues() { $expectedData = (include __DIR__ . '/_files/MetaData.php'); /** @var \Magento\SalesRule\Model\Rule|\PHPUnit_Framework_MockObject_MockObject $ruleMock */ $ruleMock = $this->getMock('Magento\\SalesRule\\Model\\Rule', [], [], '', false); $this->ruleFactoryMock->expects($this->once())->method('create')->willReturn($ruleMock); $ruleMock->expects($this->once())->method('getCouponTypes')->willReturn(['key1' => 'couponType1', 'key2' => 'couponType2']); $ruleMock->expects($this->once())->method('getStoreLabels')->willReturn(['label0']); $test = $this->model->getMetadataValues($ruleMock); $this->assertEquals($expectedData, $test); }
public function testGetById() { $model = $this->getMock('\\Magento\\SalesRule\\Model\\Rule', [], [], '', false); $this->ruleFactory->expects($this->once())->method('create')->willReturn($model); $model->expects($this->once())->method('load')->with(10)->willReturnSelf(); $model->expects($this->once())->method('getId')->willReturn(10); $model->expects($this->once())->method('getStoreLabels'); $rule = $this->getMock('\\Magento\\SalesRule\\Model\\Data\\Rule', [], [], '', false); $this->toDataModelConverter->expects($this->once())->method('toDataModel')->with($model)->willReturn($rule); $this->assertEquals($rule, $this->ruleRepository->getById(10)); }
/** * Get metadata for sales rule form. It will be merged with form UI component declaration. * * @param Rule $rule * @return array * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ public function getMetadataValues(\Magento\SalesRule\Model\Rule $rule) { $customerGroups = $this->groupRepository->getList($this->searchCriteriaBuilder->create())->getItems(); $applyOptions = [['label' => __('Percent of product price discount'), 'value' => Rule::BY_PERCENT_ACTION], ['label' => __('Fixed amount discount'), 'value' => Rule::BY_FIXED_ACTION], ['label' => __('Fixed amount discount for whole cart'), 'value' => Rule::CART_FIXED_ACTION], ['label' => __('Buy X get Y free (discount amount is Y)'), 'value' => Rule::BUY_X_GET_Y_ACTION]]; $couponTypesOptions = []; $couponTypes = $this->salesRuleFactory->create()->getCouponTypes(); foreach ($couponTypes as $key => $couponType) { $couponTypesOptions[] = ['label' => $couponType, 'value' => $key]; } $labels = $rule->getStoreLabels(); return ['rule_information' => ['children' => ['website_ids' => ['arguments' => ['data' => ['config' => ['options' => $this->store->getWebsiteValuesForForm()]]]], 'is_active' => ['arguments' => ['data' => ['config' => ['options' => [['label' => __('Active'), 'value' => '1'], ['label' => __('Inactive'), 'value' => '0']]]]]], 'customer_group_ids' => ['arguments' => ['data' => ['config' => ['options' => $this->objectConverter->toOptionArray($customerGroups, 'id', 'code')]]]], 'coupon_type' => ['arguments' => ['data' => ['config' => ['options' => $couponTypesOptions]]]], 'is_rss' => ['arguments' => ['data' => ['config' => ['options' => [['label' => __('Yes'), 'value' => '1'], ['label' => __('No'), 'value' => '0']]]]]]]], 'actions' => ['children' => ['simple_action' => ['arguments' => ['data' => ['config' => ['options' => $applyOptions]]]], 'discount_amount' => ['arguments' => ['data' => ['config' => ['value' => '0']]]], 'discount_qty' => ['arguments' => ['data' => ['config' => ['value' => '0']]]], 'apply_to_shipping' => ['arguments' => ['data' => ['config' => ['options' => [['label' => __('Yes'), 'value' => '1'], ['label' => __('No'), 'value' => '0']]]]]], 'stop_rules_processing' => ['arguments' => ['data' => ['config' => ['options' => [['label' => __('Yes'), 'value' => '1'], ['label' => __('No'), 'value' => '0']]]]]]]], 'labels' => ['children' => ['store_labels[0]' => ['arguments' => ['data' => ['config' => ['value' => isset($labels[0]) ? $labels[0] : '']]]]]]]; }
/** * Prepare chooser element HTML * * @param \Magento\Framework\Data\Form\Element\AbstractElement $element Form Element * @return \Magento\Framework\Data\Form\Element\AbstractElement */ public function prepareElementHtml(\Magento\Framework\Data\Form\Element\AbstractElement $element) { $uniqId = $this->mathRandom->getUniqueHash($element->getId()); $sourceUrl = $this->getUrl('sales_rule/promo_quote/chooser', ['uniq_id' => $uniqId]); $chooser = $this->getLayout()->createBlock('Magento\\Widget\\Block\\Adminhtml\\Widget\\Chooser')->setElement($element)->setConfig($this->getConfig())->setFieldsetId($this->getFieldsetId())->setSourceUrl($sourceUrl)->setUniqId($uniqId); if ($element->getValue()) { $rule = $this->ruleFactory->create()->load((int) $element->getValue()); if ($rule->getId()) { $chooser->setLabel($rule->getName()); } } $element->setData('after_element_html', $chooser->toHtml()); return $element; }
public function testAddSalesRuleNameToOrder() { $observer = $this->getMock('Magento\\Framework\\Event\\Observer', ['getOrder'], [], '', false); $rule = $this->getMock('Magento\\SalesRule\\Model\\Rule', ['load', 'getName', '__wakeup'], [], '', false); $order = $this->getMock('Magento\\Sales\\Model\\Order', ['setCouponRuleName', 'getCouponCode', '__wakeup'], [], '', false); $couponCode = 'coupon code'; $ruleId = 1; $observer->expects($this->any())->method('getOrder')->will($this->returnValue($order)); $order->expects($this->once())->method('getCouponCode')->will($this->returnValue($couponCode)); $this->couponMock->expects($this->once())->method('getRuleId')->will($this->returnValue($ruleId)); $this->ruleFactory->expects($this->once())->method('create')->will($this->returnValue($rule)); $rule->expects($this->once())->method('load')->with($ruleId)->will($this->returnSelf()); $order->expects($this->once())->method('setCouponRuleName'); $this->assertEquals($this->model, $this->model->execute($observer)); }
/** * Handles addition of actions tab to supplied form. * * @param \Magento\SalesRule\Model\Rule $model * @param string $fieldsetId * @param string $formName * @return \Magento\Framework\Data\Form * @throws \Magento\Framework\Exception\LocalizedException */ protected function addTabToForm($model, $fieldsetId = 'actions_fieldset', $formName = 'sales_rule_form') { if (!$model) { $id = $this->getRequest()->getParam('id'); $model = $this->ruleFactory->create(); $model->load($id); } $actionsFieldSetId = $model->getActionsFieldSetId($formName); $newChildUrl = $this->getUrl('sales_rule/promo_quote/newActionHtml/form/rule_actions_fieldset_' . $actionsFieldSetId, ['form_namespace' => $formName]); /** @var \Magento\Framework\Data\Form $form */ $form = $this->_formFactory->create(); $form->setHtmlIdPrefix('rule_'); $renderer = $this->_rendererFieldset->setTemplate('Magento_CatalogRule::promo/fieldset.phtml')->setNewChildUrl($newChildUrl)->setFieldSetId($actionsFieldSetId); $fieldset = $form->addFieldset($fieldsetId, ['legend' => __('Apply the rule only to cart items matching the following conditions ' . '(leave blank for all items).')])->setRenderer($renderer); $fieldset->addField('actions', 'text', ['name' => 'apply_to', 'label' => __('Apply To'), 'title' => __('Apply To'), 'required' => true, 'data-form-part' => $formName])->setRule($model)->setRenderer($this->_ruleActions); $this->_eventManager->dispatch('adminhtml_block_salesrule_actions_prepareform', ['form' => $form]); $form->setValues($model->getData()); $this->setActionFormName($model->getActions(), $formName); if ($model->isReadonly()) { foreach ($fieldset->getElements() as $element) { $element->setReadonly(true, true); } } return $form; }
/** * @param RuleDataModel $dataModel * @return $this|Rule * @throws \Magento\Framework\Exception\NoSuchEntityException * @throws \Magento\Framework\Exception\InputException */ public function toModel(RuleDataModel $dataModel) { $ruleId = $dataModel->getRuleId(); if ($ruleId) { $ruleModel = $this->ruleFactory->create()->load($ruleId); if (!$ruleModel->getId()) { throw new \Magento\Framework\Exception\NoSuchEntityException(); } } else { $ruleModel = $this->ruleFactory->create(); } $modelData = $ruleModel->getData(); $data = $this->dataObjectProcessor->buildOutputDataArray($dataModel, '\\Magento\\SalesRule\\Api\\Data\\RuleInterface'); $mergedData = array_merge($modelData, $data); $validateResult = $ruleModel->validateData(new \Magento\Framework\DataObject($mergedData)); if ($validateResult !== true) { $text = ''; /** @var \Magento\Framework\Phrase $errorMessage */ foreach ($validateResult as $errorMessage) { $text .= $errorMessage->getText(); $text .= '; '; } throw new \Magento\Framework\Exception\InputException(new \Magento\Framework\Phrase($text)); } $ruleModel->setData($mergedData); $this->mapFields($ruleModel, $dataModel); return $ruleModel; }
/** * {@inheritdoc} */ public function run() { $this->logger->log('Installing sales rules:'); $file = 'SalesRule/sales_rules.csv'; $fileName = $this->fixtureHelper->getPath($file); $csvReader = $this->csvReaderFactory->create(['fileName' => $fileName, 'mode' => 'r']); $attribute = $this->eavConfig->getAttribute('catalog_product', 'sku'); if ($attribute->getIsUsedForPromoRules() == 0) { $attribute->setIsUsedForPromoRules('1')->save(); } foreach ($csvReader as $row) { /** @var \Magento\SalesRule\Model\Resource\Rule\Collection $ruleCollection */ $ruleCollection = $this->ruleCollectionFactory->create(); $ruleCollection->addFilter('name', $row['name']); if ($ruleCollection->count() > 0) { continue; } $row['customer_group_ids'] = $this->catalogRule->getGroupIds(); $row['website_ids'] = $this->catalogRule->getWebsiteIds(); $row['conditions_serialized'] = $this->catalogRule->convertSerializedData($row['conditions_serialized']); $row['actions_serialized'] = $this->catalogRule->convertSerializedData($row['actions_serialized']); /** @var \Magento\SalesRule\Model\Rule $rule */ $rule = $this->ruleFactory->create(); $rule->loadPost($row); $rule->save(); $this->logger->logInline('.'); } }
/** * Generates a textual description of the applied discount rules * * @param Order $order * @return string discount description */ protected function buildDiscountRuleDescription(Order $order) { try { $appliedRules = array(); foreach ($order->getAllVisibleItems() as $item) { /* @var Item $item */ $itemAppliedRules = $item->getAppliedRuleIds(); if (empty($itemAppliedRules)) { continue; } $ruleIds = explode(',', $item->getAppliedRuleIds()); foreach ($ruleIds as $ruleId) { $rule = $this->_salesRuleFactory->create()->load($ruleId); $appliedRules[$ruleId] = $rule->getName(); } } if (count($appliedRules) == 0) { $appliedRules[] = 'unknown rule'; } $discountTxt = sprintf('Discount (%s)', implode(', ', $appliedRules)); } catch (\Exception $e) { $discountTxt = 'Discount (error)'; } return $discountTxt; }
/** * @param EventObserver $observer * @return $this * @SuppressWarnings(PHPMD.CyclomaticComplexity) */ public function execute(EventObserver $observer) { $order = $observer->getEvent()->getOrder(); if (!$order || $order->getDiscountAmount() == 0) { return $this; } // lookup rule ids $ruleIds = explode(',', $order->getAppliedRuleIds()); $ruleIds = array_unique($ruleIds); $ruleCustomer = null; $customerId = $order->getCustomerId(); // use each rule (and apply to customer, if applicable) foreach ($ruleIds as $ruleId) { if (!$ruleId) { continue; } /** @var \Magento\SalesRule\Model\Rule $rule */ $rule = $this->_ruleFactory->create(); $rule->load($ruleId); if ($rule->getId()) { $rule->loadCouponCode(); $rule->setTimesUsed($rule->getTimesUsed() + 1); $rule->save(); if ($customerId) { /** @var \Magento\SalesRule\Model\Rule\Customer $ruleCustomer */ $ruleCustomer = $this->_ruleCustomerFactory->create(); $ruleCustomer->loadByCustomerRule($customerId, $ruleId); if ($ruleCustomer->getId()) { $ruleCustomer->setTimesUsed($ruleCustomer->getTimesUsed() + 1); } else { $ruleCustomer->setCustomerId($customerId)->setRuleId($ruleId)->setTimesUsed(1); } $ruleCustomer->save(); } } } $this->_coupon->load($order->getCouponCode(), 'code'); if ($this->_coupon->getId()) { $this->_coupon->setTimesUsed($this->_coupon->getTimesUsed() + 1); $this->_coupon->save(); if ($customerId) { $this->_couponUsage->updateCustomerCouponTimesUsed($customerId, $this->_coupon->getId()); } } return $this; }
/** * @return array */ public function toOptionArray() { $options = []; $additional = ['value' => 'rule_id', 'label' => 'name']; $collection = $this->ruleFactory->create()->getResourceCollection(); foreach ($collection as $item) { if ($item->getUseAutoGeneration()) { $data = []; foreach ($additional as $code => $field) { $data[$code] = $item->getData($field); } $options[] = $data; } } array_unshift($options, ['value' => '', 'label' => __('--Please Select--')]); return $options; }
/** * Add coupon's rule name to order data * * @param EventObserver $observer * @return $this */ public function execute(EventObserver $observer) { $order = $observer->getOrder(); $couponCode = $order->getCouponCode(); if (empty($couponCode)) { return $this; } $this->_coupon->loadByCode($couponCode); $ruleId = $this->_coupon->getRuleId(); if (empty($ruleId)) { return $this; } /** @var \Magento\SalesRule\Model\Rule $rule */ $rule = $this->_ruleFactory->create()->load($ruleId); $order->setCouponRuleName($rule->getName()); return $this; }
/** * Delete sales rule by ID. * * @param int $id * @return bool true on success * @throws \Magento\Framework\Exception\NoSuchEntityException * @throws \Magento\Framework\Exception\LocalizedException */ public function deleteById($id) { $model = $this->ruleFactory->create()->load($id); if (!$model->getId()) { throw new \Magento\Framework\Exception\NoSuchEntityException(); } $model->delete(); return true; }
/** * Prepare form before rendering HTML * * @return $this * @SuppressWarnings(PHPMD.NPathComplexity) * @SuppressWarnings(PHPMD.ExcessiveMethodLength) */ protected function _prepareForm() { $model = $this->_coreRegistry->registry('current_promo_quote_rule'); /** @var \Magento\Framework\Data\Form $form */ $form = $this->_formFactory->create(); $form->setHtmlIdPrefix('rule_'); $fieldset = $form->addFieldset('base_fieldset', ['legend' => __('General Information')]); if ($model->getId()) { $fieldset->addField('rule_id', 'hidden', ['name' => 'rule_id']); } $fieldset->addField('product_ids', 'hidden', ['name' => 'product_ids']); $fieldset->addField('name', 'text', ['name' => 'name', 'label' => __('Rule Name'), 'title' => __('Rule Name'), 'required' => true]); $fieldset->addField('description', 'textarea', ['name' => 'description', 'label' => __('Description'), 'title' => __('Description'), 'style' => 'height: 100px;']); $fieldset->addField('is_active', 'select', ['label' => __('Status'), 'title' => __('Status'), 'name' => 'is_active', 'required' => true, 'options' => ['1' => __('Active'), '0' => __('Inactive')]]); if (!$model->getId()) { $model->setData('is_active', '1'); } if ($this->_storeManager->isSingleStoreMode()) { $websiteId = $this->_storeManager->getStore(true)->getWebsiteId(); $fieldset->addField('website_ids', 'hidden', ['name' => 'website_ids[]', 'value' => $websiteId]); $model->setWebsiteIds($websiteId); } else { $field = $fieldset->addField('website_ids', 'multiselect', ['name' => 'website_ids[]', 'label' => __('Websites'), 'title' => __('Websites'), 'required' => true, 'values' => $this->_systemStore->getWebsiteValuesForForm()]); $renderer = $this->getLayout()->createBlock('Magento\\Backend\\Block\\Store\\Switcher\\Form\\Renderer\\Fieldset\\Element'); $field->setRenderer($renderer); } $groups = $this->groupRepository->getList($this->_searchCriteriaBuilder->create())->getItems(); $fieldset->addField('customer_group_ids', 'multiselect', ['name' => 'customer_group_ids[]', 'label' => __('Customer Groups'), 'title' => __('Customer Groups'), 'required' => true, 'values' => $this->_objectConverter->toOptionArray($groups, 'id', 'code')]); $couponTypeFiled = $fieldset->addField('coupon_type', 'select', ['name' => 'coupon_type', 'label' => __('Coupon'), 'required' => true, 'options' => $this->_salesRule->create()->getCouponTypes()]); $couponCodeFiled = $fieldset->addField('coupon_code', 'text', ['name' => 'coupon_code', 'label' => __('Coupon Code'), 'required' => true]); $autoGenerationCheckbox = $fieldset->addField('use_auto_generation', 'checkbox', ['name' => 'use_auto_generation', 'label' => __('Use Auto Generation'), 'note' => __('If you select and save the rule you will be able to generate multiple coupon codes.'), 'onclick' => 'handleCouponsTabContentActivity()', 'checked' => (int) $model->getUseAutoGeneration() > 0 ? 'checked' : '']); $autoGenerationCheckbox->setRenderer($this->getLayout()->createBlock('Magento\\SalesRule\\Block\\Adminhtml\\Promo\\Quote\\Edit\\Tab\\Main\\Renderer\\Checkbox')); $usesPerCouponFiled = $fieldset->addField('uses_per_coupon', 'text', ['name' => 'uses_per_coupon', 'label' => __('Uses per Coupon')]); $fieldset->addField('uses_per_customer', 'text', ['name' => 'uses_per_customer', 'label' => __('Uses per Customer'), 'note' => __('Usage limit enforced for logged in customers only.')]); $dateFormat = $this->_localeDate->getDateFormat(\IntlDateFormatter::SHORT); $fieldset->addField('from_date', 'date', ['name' => 'from_date', 'label' => __('From'), 'title' => __('From'), 'input_format' => \Magento\Framework\Stdlib\DateTime::DATE_INTERNAL_FORMAT, 'date_format' => $dateFormat]); $fieldset->addField('to_date', 'date', ['name' => 'to_date', 'label' => __('To'), 'title' => __('To'), 'input_format' => \Magento\Framework\Stdlib\DateTime::DATE_INTERNAL_FORMAT, 'date_format' => $dateFormat]); $fieldset->addField('sort_order', 'text', ['name' => 'sort_order', 'label' => __('Priority')]); $fieldset->addField('is_rss', 'select', ['label' => __('Public In RSS Feed'), 'title' => __('Public In RSS Feed'), 'name' => 'is_rss', 'options' => ['1' => __('Yes'), '0' => __('No')]]); if (!$model->getId()) { //set the default value for is_rss feed to yes for new promotion $model->setIsRss(1); } $form->setValues($model->getData()); $autoGenerationCheckbox->setValue(1); if ($model->isReadonly()) { foreach ($fieldset->getElements() as $element) { $element->setReadonly(true, true); } } //$form->setUseContainer(true); $this->setForm($form); // field dependencies $this->setChild('form_after', $this->getLayout()->createBlock('Magento\\Backend\\Block\\Widget\\Form\\Element\\Dependence')->addFieldMap($couponTypeFiled->getHtmlId(), $couponTypeFiled->getName())->addFieldMap($couponCodeFiled->getHtmlId(), $couponCodeFiled->getName())->addFieldMap($autoGenerationCheckbox->getHtmlId(), $autoGenerationCheckbox->getName())->addFieldMap($usesPerCouponFiled->getHtmlId(), $usesPerCouponFiled->getName())->addFieldDependence($couponCodeFiled->getName(), $couponTypeFiled->getName(), \Magento\SalesRule\Model\Rule::COUPON_TYPE_SPECIFIC)->addFieldDependence($autoGenerationCheckbox->getName(), $couponTypeFiled->getName(), \Magento\SalesRule\Model\Rule::COUPON_TYPE_SPECIFIC)->addFieldDependence($usesPerCouponFiled->getName(), $couponTypeFiled->getName(), \Magento\SalesRule\Model\Rule::COUPON_TYPE_SPECIFIC)); $this->_eventManager->dispatch('adminhtml_promo_quote_edit_tab_main_prepare_form', ['form' => $form]); return parent::_prepareForm(); }
public function testToModel() { /** * @var \Magento\SalesRule\Model\Data\Rule $dataModel */ $dataModel = $this->getMockBuilder('\\Magento\\SalesRule\\Model\\Data\\Rule')->disableOriginalConstructor()->setMethods(['create', 'load', 'getData', 'getRuleId', 'getCondition', 'getActionCondition', 'getStoreLabels'])->getMock(); $dataModel->expects($this->atLeastOnce())->method('getRuleId')->willReturn(1); $dataModel->expects($this->atLeastOnce())->method('getCondition')->willReturn(false); $dataModel->expects($this->atLeastOnce())->method('getActionCondition')->willReturn(false); $dataModel->expects($this->atLeastOnce())->method('getStoreLabels')->willReturn([]); $ruleModel = $this->getMockBuilder('\\Magento\\SalesRule\\Model\\Rule')->disableOriginalConstructor()->setMethods(['create', 'load', 'getId', 'getData'])->getMock(); $ruleModel->expects($this->atLeastOnce())->method('load')->willReturn($ruleModel); $ruleModel->expects($this->atLeastOnce())->method('getId')->willReturn(1); $ruleModel->expects($this->atLeastOnce())->method('getData')->willReturn(['data_1' => 1]); $this->dataObjectProcessor->expects($this->any())->method('buildOutputDataArray')->willReturn(['data_2' => 2]); $this->ruleFactory->expects($this->any())->method('create')->willReturn($ruleModel); $result = $this->model->toModel($dataModel); $this->assertEquals($ruleModel, $result); }
/** * @dataProvider expectedDatesProvider */ public function testFormattingDate($data) { /** * @var \Magento\SalesRule\Model\Data\Rule|\PHPUnit_Framework_MockObject_MockObject $dataModel */ $dataModel = $this->getMockBuilder(\Magento\SalesRule\Model\Data\Rule::class)->disableOriginalConstructor()->setMethods(['create', 'load', 'getData', 'getRuleId', 'getCondition', 'getActionCondition', 'getStoreLabels', 'getFromDate', 'setFromDate', 'getToDate', 'setToDate'])->getMock(); $dataModel->expects($this->atLeastOnce())->method('getRuleId')->willReturn(null); $dataModel->expects($this->atLeastOnce())->method('getCondition')->willReturn(false); $dataModel->expects($this->atLeastOnce())->method('getActionCondition')->willReturn(false); $dataModel->expects($this->atLeastOnce())->method('getStoreLabels')->willReturn([]); $ruleModel = $this->getMockBuilder('\\Magento\\SalesRule\\Model\\Rule')->disableOriginalConstructor()->setMethods(['create', 'load', 'getId', 'getData'])->getMock(); $ruleModel->expects($this->atLeastOnce())->method('getData')->willReturn(['data_1' => 1]); $this->dataObjectProcessor->expects($this->any())->method('buildOutputDataArray')->willReturn(['data_2' => 2]); $this->ruleFactory->expects($this->any())->method('create')->willReturn($ruleModel); $dataModel->expects($this->atLeastOnce())->method('getFromDate')->willReturn($data['from_date']); $dataModel->expects($this->atLeastOnce())->method('getToDate')->willReturn($data['to_date']); $dataModel->expects($this->atLeastOnce())->method('setFromDate')->with($data['expected_from_date']); $dataModel->expects($this->atLeastOnce())->method('setToDate')->with($data['expected_to_date']); $this->model->toModel($dataModel); }
/** * Generates the coupon code based on the code id. * * @return bool */ public function generateCoupon() { $params = $this->getRequest()->getParams(); //check for param code and id if (!isset($params['id']) || !isset($params['code'])) { $this->helper->log('Coupon no id or code is set'); return false; } //coupon rule id $couponCodeId = $params['id']; if ($couponCodeId) { $rule = $this->ruleFactory->create()->load($couponCodeId); $generator = $this->massGeneratorFactory->create(); $generator->setFormat(\Magento\SalesRule\Helper\Coupon::COUPON_FORMAT_ALPHANUMERIC); $generator->setRuleId($couponCodeId); $generator->setUsesPerCoupon(1); $generator->setDash(3); $generator->setLength(9); $generator->setPrefix('DOT-'); $generator->setSuffix(''); //set the generation settings $rule->setCouponCodeGenerator($generator); $rule->setCouponType(\Magento\SalesRule\Model\Rule::COUPON_TYPE_AUTO); //generate the coupon $coupon = $rule->acquireCoupon(); $couponCode = $coupon->getCode(); //save the type of coupon /** @var \Magento\SalesRule\Model\Coupon $couponModel */ $couponModel = $this->couponFactory->create()->loadByCode($couponCode); $couponModel->setType(\Magento\SalesRule\Model\Rule::COUPON_TYPE_NO_COUPON)->setGeneratedByDotmailer(1); if (is_numeric($params['expire_days'])) { $expireDate = $this->_localeDate->date()->add(new \DateInterval(sprintf('P%sD', $params['expire_days']))); $couponModel->setExpirationDate($expireDate); } elseif ($rule->getToDate()) { $couponModel->setExpirationDate($rule->getToDate()); } $this->coupon->save($couponModel); return $couponCode; } return false; }
/** * {@inheritdoc} */ public function run() { $this->logger->log('Installing sales rules:'); $file = 'SalesRule/sales_rules.csv'; $fileName = $this->fixtureHelper->getPath($file); $csvReader = $this->csvReaderFactory->create(['fileName' => $fileName, 'mode' => 'r']); $attribute = $this->eavConfig->getAttribute('catalog_product', 'sku'); if ($attribute->getIsUsedForPromoRules() == 0) { $attribute->setIsUsedForPromoRules('1')->save(); } foreach ($csvReader as $row) { $row['customer_group_ids'] = $this->catalogRule->getGroupIds(); $row['website_ids'] = $this->catalogRule->getWebsiteIds(); $row['conditions_serialized'] = $this->catalogRule->convertSerializedData($row['conditions_serialized']); $row['actions_serialized'] = $this->catalogRule->convertSerializedData($row['actions_serialized']); $rule = $this->ruleFactory->create(); $rule->loadPost($row); $rule->save(); $this->logger->logInline('.'); } }
/** * Generate coupon for a rule * * @param \Magento\SalesRule\Api\Data\CouponGenerationSpecInterface $couponSpec * @return string[] * @throws \Magento\Framework\Exception\InputException * @throws \Magento\Framework\Exception\LocalizedException */ public function generate(\Magento\SalesRule\Api\Data\CouponGenerationSpecInterface $couponSpec) { $data = $this->convertCouponSpec($couponSpec); if (!$this->couponGenerator->validateData($data)) { throw new \Magento\Framework\Exception\InputException(); } try { $rule = $this->ruleFactory->create()->load($couponSpec->getRuleId()); if (!$rule->getRuleId()) { throw \Magento\Framework\Exception\NoSuchEntityException::singleField(\Magento\SalesRule\Model\Coupon::KEY_RULE_ID, $couponSpec->getRuleId()); } if (!$rule->getUseAutoGeneration()) { throw new \Magento\Framework\Exception\LocalizedException(__('Specified rule does not allow automatic coupon generation')); } $this->couponGenerator->setData($data); $this->couponGenerator->setData('to_date', $rule->getToDate()); $this->couponGenerator->setData('uses_per_coupon', $rule->getUsesPerCoupon()); $this->couponGenerator->setData('usage_per_customer', $rule->getUsesPerCustomer()); $this->couponGenerator->generatePool(); return $this->couponGenerator->getGeneratedCodes(); } catch (\Exception $e) { throw new \Magento\Framework\Exception\LocalizedException(__('Error occurred when generating coupons: %1', $e->getMessage())); } }
/** * Handles addition of conditions tab to supplied form. * * @param \Magento\SalesRule\Model\Rule $model * @param string $fieldsetId * @param string $formName * @return \Magento\Framework\Data\Form * @throws \Magento\Framework\Exception\LocalizedException */ protected function addTabToForm($model, $fieldsetId = 'conditions_fieldset', $formName = 'sales_rule_form') { if (!$model) { $id = $this->getRequest()->getParam('id'); $model = $this->ruleFactory->create(); $model->load($id); } $conditionsFieldSetId = $model->getConditionsFieldSetId($formName); $newChildUrl = $this->getUrl('sales_rule/promo_quote/newConditionHtml/form/' . $conditionsFieldSetId, ['form_namespace' => $formName]); /** @var \Magento\Framework\Data\Form $form */ $form = $this->_formFactory->create(); $form->setHtmlIdPrefix('rule_'); $renderer = $this->_rendererFieldset->setTemplate('Magento_CatalogRule::promo/fieldset.phtml')->setNewChildUrl($newChildUrl)->setFieldSetId($conditionsFieldSetId); $fieldset = $form->addFieldset($fieldsetId, ['legend' => __('Apply the rule only if the following conditions are met (leave blank for all products).')])->setRenderer($renderer); $fieldset->addField('conditions', 'text', ['name' => 'conditions', 'label' => __('Conditions'), 'title' => __('Conditions'), 'required' => true, 'data-form-part' => $formName])->setRule($model)->setRenderer($this->_conditions); $form->setValues($model->getData()); $this->setConditionFormName($model->getConditions(), $formName); return $form; }
/** * Prepare form before rendering HTML * * @return $this */ protected function _prepareForm() { $rule = $this->_coreRegistry->registry(\Magento\SalesRule\Model\RegistryConstants::CURRENT_SALES_RULE); if (!$rule) { $id = $this->getRequest()->getParam('id'); $rule = $this->ruleFactory->create(); $rule->load($id); } /** @var \Magento\Framework\Data\Form $form */ $form = $this->_formFactory->create(); $form->setHtmlIdPrefix('rule_'); $labels = $rule->getStoreLabels(); if (!$this->_storeManager->isSingleStoreMode()) { $fieldset = $this->_createStoreSpecificFieldset($form, $labels); if ($rule->isReadonly()) { foreach ($fieldset->getElements() as $element) { $element->setReadonly(true, true); } } } $this->setForm($form); return parent::_prepareForm(); }
/** * @param int|bool $ruleCustomerId * @dataProvider salesOrderAfterPlaceDataProvider */ public function testSalesOrderAfterPlace($ruleCustomerId) { $observer = $this->getMock('Magento\\Framework\\Event\\Observer', [], [], '', false); $rule = $this->getMock('Magento\\SalesRule\\Model\\Rule', [], [], '', false); $ruleCustomer = $this->getMock('Magento\\SalesRule\\Model\\Rule\\Customer', ['setCustomerId', 'loadByCustomerRule', 'getId', 'setTimesUsed', 'setRuleId', 'save', '__wakeup'], [], '', false); $order = $this->initOrderFromEvent($observer); $ruleId = 1; $couponId = 1; $customerId = 1; $discountAmount = 10; $order->expects($this->once())->method('getAppliedRuleIds')->will($this->returnValue($ruleId)); $order->expects($this->once())->method('getDiscountAmount')->will($this->returnValue($discountAmount)); $order->expects($this->once())->method('getCustomerId')->will($this->returnValue($customerId)); $this->ruleFactory->expects($this->once())->method('create')->will($this->returnValue($rule)); $rule->expects($this->once())->method('getId')->will($this->returnValue($ruleId)); $this->ruleCustomerFactory->expects($this->once())->method('create')->will($this->returnValue($ruleCustomer)); $ruleCustomer->expects($this->once())->method('getId')->will($this->returnValue($ruleCustomerId)); $ruleCustomer->expects($this->any())->method('setCustomerId')->will($this->returnSelf()); $ruleCustomer->expects($this->any())->method('setRuleId')->will($this->returnSelf()); $this->couponMock->expects($this->any())->method('getId')->will($this->returnValue($couponId)); $this->couponUsage->expects($this->once())->method('updateCustomerCouponTimesUsed')->with($customerId, $couponId); $this->assertEquals($this->model, $this->model->execute($observer)); }
/** * {@inheritdoc} */ public function install(array $fixtures) { $attribute = $this->eavConfig->getAttribute('catalog_product', 'sku'); if ($attribute->getIsUsedForPromoRules() == 0) { $attribute->setIsUsedForPromoRules('1')->save(); } foreach ($fixtures as $fileName) { $fileName = $this->fixtureManager->getFixture($fileName); if (!file_exists($fileName)) { continue; } $rows = $this->csvReader->getData($fileName); $header = array_shift($rows); foreach ($rows as $row) { $data = []; foreach ($row as $key => $value) { $data[$header[$key]] = $value; } $row = $data; /** @var \Magento\SalesRule\Model\ResourceModel\Rule\Collection $ruleCollection */ $ruleCollection = $this->ruleCollectionFactory->create(); $ruleCollection->addFilter('name', $row['name']); if ($ruleCollection->count() > 0) { continue; } $row['customer_group_ids'] = $this->catalogRule->getGroupIds(); $row['website_ids'] = $this->catalogRule->getWebsiteIds(); $row['conditions_serialized'] = $this->catalogRule->convertSerializedData($row['conditions_serialized']); $row['actions_serialized'] = $this->catalogRule->convertSerializedData($row['actions_serialized']); /** @var \Magento\SalesRule\Model\Rule $rule */ $rule = $this->ruleFactory->create(); $rule->loadPost($row); $rule->save(); } } }
/** * @param \Magento\SalesRule\Model\RuleFactory $modelFactory * @param array $categoriesArray * @return void */ public function generateAdvancedRules($modelFactory, $categoriesArray) { $j = 0; for ($i = 0; $i < $this->cartPriceRulesCount; $i++) { if ($i < $this->cartPriceRulesCount - 200) { $ruleName = sprintf('Cart Price Advanced Catalog Rule %1$d', $j); } else { $ruleName = sprintf('Cart Price Advanced Region Rule %1$d', $j); } $j++; $data = ['rule_id' => null, 'product_ids' => '', 'name' => $ruleName, 'description' => '', 'is_active' => '1', 'website_ids' => $categoriesArray[$i % count($categoriesArray)][1], 'customer_group_ids' => [0 => '0', 1 => '1', 2 => '2', 3 => '3'], 'coupon_type' => '1', 'coupon_code' => '', 'uses_per_customer' => '', 'from_date' => '', 'to_date' => '', 'sort_order' => '', 'is_rss' => '1', 'rule' => $this->generateAdvancedCondition($i, $categoriesArray), 'simple_action' => 'cart_fixed', 'discount_amount' => '1', 'discount_qty' => '0', 'discount_step' => '', 'apply_to_shipping' => '0', 'simple_free_shipping' => '0', 'stop_rules_processing' => '0', 'reward_points_delta' => '', 'store_labels' => [0 => '', 1 => '', 2 => '', 3 => '', 4 => '', 5 => '', 6 => '', 7 => '', 8 => '', 9 => '', 10 => '', 11 => ''], 'page' => '1', 'limit' => '20', 'in_banners' => '', 'banner_id' => ['from' => '', 'to' => ''], 'banner_name' => '', 'visible_in' => '', 'banner_is_enabled' => '', 'related_banners' => []]; if (isset($data['simple_action']) && $data['simple_action'] == 'cart_fixed' && isset($data['discount_amount'])) { $data['discount_amount'] = min(1, $data['discount_amount']); } if (isset($data['rule']['conditions'])) { $data['conditions'] = $data['rule']['conditions']; } if (isset($data['rule']['actions'])) { $data['actions'] = $data['rule']['actions']; } unset($data['rule']); $model = $modelFactory->create(); $model->loadPost($data); $useAutoGeneration = (int) (!empty($data['use_auto_generation'])); $model->setUseAutoGeneration($useAutoGeneration); $model->save(); } }