In Magento 2 Enterprise edition how can i add the reward point for a customer?
Thank you very much.
For example we want to assign the reward points when customer save event (customer_save_after_data_object) observer is called then it will be like this
namespace Aizar\CustomerStatus\Observer;
use Magento\Framework\Event\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Reward\Model\Reward;
use Magento\Reward\Model\Reward\HistoryFactory;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Message\ManagerInterface;
use Magento\Reward\Model\RewardFactory;
class CustomerSaveObserver implements ObserverInterface
{
/**
* @var \Magento\Framework\Message\ManagerInterface
*/
protected $messageManager;
/**
* Reward factory
*
* @var \Magento\Reward\Model\RewardFactory
*/
protected $_rewardFactory;
/**
* Store manager
*
* @var StoreManagerInterface
*/
protected $_storeManager;
public function __construct(RewardFactory $rewardFactory,
StoreManagerInterface $storeManager,
ManagerInterface $messageManager)
{
$this->messageManager = $messageManager;
$this->_rewardFactory = $rewardFactory;
$this->_storeManager = $storeManager;
}
/**
*
* @param Observer $observer
* @return void
*/
public function execute(Observer $observer)
{
/* @var $reward \Magento\Reward\Model\Reward */
$newCustomerData = $observer->getCustomerDataObject();
$websiteId = $this->_storeManager->getWebsite()->getId();
$reward = $this->_rewardFactory->create()->setCustomer($newCustomerData)
->setCustomerId($newCustomerData->getId())
->setWebsiteId($websiteId)
->loadByCustomer()
->setAction(\Magento\Reward\Model\Reward::REWARD_ACTION_ADMIN)
->setComment(__('Additional Information Reward'))
->updateRewardPoints();
$this->messageManager->addNoticeMessage(__('You have got %1 reward pints', $reward->getPointsDelta()));
}
}
I hope it will help someone. Please vote up my answer if it will help you. Thank you very much.
app/code/Vendor/CustomReward/Controller/Adminhtml/Order/Create/Save.php
<?php
declare(strict_types=1);
namespace Vendor\CustomReward\Controller\Adminhtml\Order\Create;
use Exception;
use Magento\Backend\App\Action;
use Magento\Backend\Model\Session\Quote;
use Magento\Backend\Model\View\Result\ForwardFactory;
use Magento\Catalog\Helper\Product;
use Magento\Framework\App\Action\HttpPostActionInterface as HttpPostActionInterface;
use Magento\Framework\Controller\ResultInterface;
use Magento\Framework\Escaper;
use Magento\Framework\Exception\InputException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Exception\PaymentException;
use Magento\Framework\View\Result\PageFactory;
use Magento\Payment\Model\Method\AbstractMethod;
use Magento\Quote\Model\Quote\Address\Total;
use Magento\Reward\Model\Reward;
use Magento\Reward\Model\Reward\History;
use Magento\Reward\Model\RewardFactory;
use Magento\Framework\Pricing\PriceCurrencyInterface;
class Save extends \Magento\Sales\Controller\Adminhtml\Order\Create\Save
{
/**
* @var Action\Context
*/
private $context;
/**
* @var Product
*/
private $productHelper;
/**
* @var Quote
*/
private $quoteBackendSession;
/**
* @var History
*/
private $rewardHistory;
/**
* @var Reward
*/
private $rewardFactory;
/**
* @var PriceCurrencyInterface
*/
private $priceCurrency;
/**
* Saving quote and create order
*
* @param Action\Context $context
* @param PriceCurrencyInterface $priceCurrency
* @param History $rewardHistory
* @param RewardFactory $rewardFactory
* @param Quote $quoteBackendSession
* @param Product $productHelper
* @param Escaper $escaper
* @param PageFactory $resultPageFactory
* @param ForwardFactory $resultForwardFactory
* @SuppressWarnings(PHPMD.CyclomaticComplexity)
*/
public function __construct(Action\Context $context, PriceCurrencyInterface $priceCurrency , History $rewardHistory, RewardFactory $rewardFactory, Quote $quoteBackendSession, Product $productHelper, Escaper $escaper, PageFactory $resultPageFactory, ForwardFactory $resultForwardFactory)
{
parent::__construct($context, $productHelper, $escaper, $resultPageFactory, $resultForwardFactory);
$this->context = $context;
$this->productHelper = $productHelper;
$this->escaper = $escaper;
$this->resultPageFactory = $resultPageFactory;
$this->resultForwardFactory = $resultForwardFactory;
$this->quoteBackendSession = $quoteBackendSession;
$this->rewardHistory = $rewardHistory;
$this->rewardFactory = $rewardFactory;
$this->priceCurrency = $priceCurrency;
}
public function execute()
{
$path = 'sales/*/';
$pathParams = [];
try {
// check if the creation of a new customer is allowed
if (!$this->_authorization->isAllowed('Magento_Customer::manage')
&& !$this->_getSession()->getCustomerId()
&& !$this->_getSession()->getQuote()->getCustomerIsGuest()
) {
return $this->resultForwardFactory->create()->forward('denied');
}
if ($this->quoteBackendSession->getQuote()->getUseRewardPoints() == true){
$quote = $this->quoteBackendSession->getQuote();
$customer = $quote->getCustomer();
$reward = $this->rewardFactory->create()->setCustomer($customer);
$reward->setWebsiteId($quote->getStore()->getWebsiteId());
$reward->loadByCustomer();
$getPointBalance = $reward->getPointsBalance();
}
$payment = $this->getRequest()->getParam('payment');
if ($this->quoteBackendSession->getQuote()->getUseRewardPoints() == false) {
unset($payment['custom_reward']);
}else{
$customReward = $payment['custom_reward'];
}
if ($this->quoteBackendSession->getQuote()->getUseRewardPoints() == false) {
$this->_getOrderCreateModel()->getQuote()->setCustomerId($this->_getSession()->getCustomerId());
} elseif($customReward > $getPointBalance) {
throw new InputException(__("No Enough Reward points"));
}else{
$customReward = $payment['custom_reward'];
$this->_getOrderCreateModel()->getQuote()->setCustomerId($this->_getSession()->getCustomerId());
$this->_getOrderCreateModel()->getQuote()->setData('reward_points_balance', $customReward);
$this->_getOrderCreateModel()->getQuote()->setData('base_reward_currency_amount', $customReward);
$this->_getOrderCreateModel()->getQuote()->setData('reward_currency_amount', $customReward);
$this->_getOrderCreateModel()->getQuote()->setData('payment_by_reward_points', $customReward);
$this->_getOrderCreateModel()->getQuote()->setData('points_used', $customReward);
$this->_getOrderCreateModel()->getQuote()->collectTotals();
$this->_getOrderCreateModel()->getQuote()->save();
}
$this->_processActionData('save');
$paymentData = $this->getRequest()->getPost('payment');
if ($paymentData) {
$paymentData['checks'] = [
AbstractMethod::CHECK_USE_INTERNAL,
AbstractMethod::CHECK_USE_FOR_COUNTRY,
AbstractMethod::CHECK_USE_FOR_CURRENCY,
AbstractMethod::CHECK_ORDER_TOTAL_MIN_MAX,
AbstractMethod::CHECK_ZERO_TOTAL,
];
$this->_getOrderCreateModel()->setPaymentData($paymentData);
$this->_getOrderCreateModel()->getQuote()->getPayment()->addData($paymentData);
}
if ($this->quoteBackendSession->getQuote()->getUseRewardPoints() == false) {
$order = $this->_getOrderCreateModel()
->setIsValidate(true)
->importPostData($this->getRequest()->getPost('order'))
->createOrder();
}else{
$order = $this->_getOrderCreateModel()
->setIsValidate(true)
->importPostData($this->getRequest()->getPost('order'))
->createOrder();
$order->setRewardPointsBalance($customReward);
$order->setBaseRewardCurrencyAmount($customReward);
$order->setRewardCurrencyAmount($customReward);
$order->setPaymentByRewardPoints($customReward);
$order->setPointsUsed($customReward);
$order->save();
}
$this->rewardHistoryOrder($this->quoteBackendSession->getQuote(), $order);
$this->_getSession()->clearStorage();
$this->messageManager->addSuccessMessage(__('You created the order.'));
if ($this->_authorization->isAllowed('Magento_Sales::actions_view')) {
$pathParams = ['order_id' => $order->getId()];
$path = 'sales/order/view';
} else {
$path = 'sales/order/index';
}
} catch (PaymentException $e) {
$this->_getOrderCreateModel()->saveQuote();
$message = $e->getMessage();
if (!empty($message)) {
$this->messageManager->addErrorMessage($message);
}
} catch (LocalizedException $e) {
// customer can be created before place order flow is completed and should be stored in current session
$this->_getSession()->setCustomerId((int)$this->_getSession()->getQuote()->getCustomerId());
$message = $e->getMessage();
if (!empty($message)) {
$this->messageManager->addErrorMessage($message);
}
} catch (Exception $e) {
$this->messageManager->addExceptionMessage($e, __('Order saving error: %1', $e->getMessage()));
}
return $this->resultRedirectFactory->create()->setPath($path, $pathParams);
}
public function rewardHistoryOrder($quote, $order){
$customer = $quote->getCustomer();
$reward = $quote->getRewardInstance();
if (!$reward || !$reward->getId()) {
$reward = $this->rewardFactory->create()->setCustomer($customer);
$reward->setWebsiteId($quote->getStore()->getWebsiteId());
$reward->loadByCustomer();
$reward->setUsed($quote->getPointBalance());
$reward->getPointBalance();
}
$setDeltaPoints = (-1 * $quote->getRewardPointsBalance());
$pointLeft = $reward->getPointsBalance();
$reward->setPointsBalance($pointLeft);
$reward->setPointsDelta($setDeltaPoints)->setIsCappedReward(true)->updateRewardPoints();
return $this;
}
}
app/code/Vendor/CustomReward/etc/adminhtml/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
<preference for="Magento\Sales\Controller\Adminhtml\Order\Create\Save"
type="Vendor\CustomReward\Controller\Adminhtml\Order\Create\Save" />
</config>
app/code/Vendor/CustomReward/view/adminhtml/templates/sales/order/create/payment.phtml
canUseRewardPoints()) :?><div class="admin__field admin__field-option">
<input id="p_method_use_reward_points"
class="admin__control-checkbox"
value="1"
name="payment[use_reward_points]"
type="checkbox"
<?php if ($block->useRewardPoints() ) :?>checked="checked"<?php endif; ?> />
<label class="admin__field-label" for="p_method_use_reward_points">
<?= $block->escapeHtml($block->getUseLabel(), ['span']); ?>
</label>
<script>
require(['jquery', 'domReady!'], function($) {
var toggleUseRewardPoints = function () {
var checked = $(this).is(':checked') ? 1 : 0;
var data = {};
data['payment[use_reward_points]'] = checked;
order.loadArea(['totals', 'billing_method'], true, data);
};
var refundRewardPointsEnable = $('#p_method_use_reward_points');
refundRewardPointsEnable.change(toggleUseRewardPoints);
});
</script>
</div>
<?php if ($block->canUseRewardPoints()) :?>
<?php if ($block->useRewardPoints() ) :?>
<div class="test">
<input type="text" class="admin__control-text required-entry _required" name="payment[custom_reward]" id="custom_reward_set">
<button id="submit_reward" class="action-default scalable action-secondary" >
Apply
</button>
</div>
<?php endif; ?>
<script>
require(['jquery', 'domReady!'], function($) {
if ($('#p_method_use_reward_points').prop('checked')) {
$('.test').show();
console.log('working');
}else{
$('.test').hide();
console.log('not working');
}
$('#submit_reward').on('click', function (e){
let getPoints = $('#custom_reward_set').val();
let checkField = $('#custom_reward_set').prop("readonly");
// alert(getPoints);
if (!getPoints){
alert('PLease add reward points');
}
if (getPoints) {
$("#custom_reward_set").prop("readonly", !$("#custom_reward_set").attr('readonly'));
if ($('#custom_reward_set').is('[readonly]')) {
$("#custom_reward_set").css({
"background-color": "#EBEBE4",
"border": "1px solid #ABADB3", "cursor": "not-allowed"
});
}else{
$('#custom_reward_set').removeAttr('style');
}
}
e.preventDefault();
})
});
</script>
<?php endif; ?>