This commit is contained in:
2026-09-15 10:35:56 +08:00
commit 782f8ea7aa
4086 changed files with 631288 additions and 0 deletions
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace Esun\Reward\Controller\Account;
use Magento\Customer\Controller\AbstractAccount;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\View\Result\PageFactory;
use Magento\Framework\App\Action\Context;
class Index extends AbstractAccount implements HttpGetActionInterface
{
public function __construct(Context $context, private readonly PageFactory $pageFactory) { parent::__construct($context); }
public function execute() { $page = $this->pageFactory->create(); $page->getConfig()->getTitle()->set(__('My Points')); return $page; }
}
@@ -0,0 +1,37 @@
<?php
declare(strict_types=1);
namespace Esun\Reward\Controller\Adminhtml\Customer;
use Esun\Reward\Model\BalanceManager;
use Magento\Backend\App\Action;
use Magento\Backend\Model\Auth\Session as AuthSession;
use Magento\Customer\Api\CustomerRepositoryInterface;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Math\Random;
class Adjust extends Action
{
public const ADMIN_RESOURCE = 'Esun_Reward::adjust';
public function __construct(Action\Context $context, private readonly BalanceManager $balanceManager, private readonly CustomerRepositoryInterface $customers, private readonly AuthSession $authSession, private readonly Random $random) { parent::__construct($context); }
public function execute()
{
$customerId = (int)$this->getRequest()->getParam('customer_id');
$redirect = $this->resultRedirectFactory->create()->setPath('customer/index/edit', ['id' => $customerId, '_current' => true]);
try {
$points = abs((int)$this->getRequest()->getParam('points')); $operation = (string)$this->getRequest()->getParam('operation');
$reason = trim((string)$this->getRequest()->getParam('reason')); $evidence = trim((string)$this->getRequest()->getParam('evidence'));
if ($customerId <= 0 || $points <= 0) { throw new LocalizedException(__('Enter a positive number of points.')); }
if ($reason === '') { throw new LocalizedException(__('A reason is required.')); }
$adjustmentType = (string)$this->getRequest()->getParam('adjustment_type');
$type = $adjustmentType === 'social_share' ? 'social_share' : 'admin_adjustment';
$delta = $operation === 'subtract' ? -$points : $points; $customer = $this->customers->getById($customerId); $admin = $this->authSession->getUser();
$this->balanceManager->change($customerId, (int)$customer->getWebsiteId(), $delta, $type, $type . ':' . $this->random->getUniqueHash(), [
'reference_type' => 'admin', 'reference_id' => $admin ? (int)$admin->getId() : null, 'reason' => $reason,
'admin_user_id' => $admin ? (int)$admin->getId() : null, 'metadata' => $evidence === '' ? [] : ['evidence' => $evidence]
]);
$this->messageManager->addSuccessMessage(__('The reward points were adjusted.'));
} catch (\Throwable $e) { $this->messageManager->addErrorMessage($e->getMessage()); }
return $redirect;
}
}
@@ -0,0 +1,46 @@
<?php
declare(strict_types=1);
namespace Esun\Reward\Controller\Cart;
use Esun\Reward\Model\BalanceManager;
use Esun\Reward\Model\Config;
use Esun\Reward\Model\ReservationManager;
use Magento\Checkout\Model\Session;
use Magento\Checkout\Helper\Data as CheckoutHelper;
use Magento\Customer\Model\Session as CustomerSession;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\JsonFactory;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Quote\Api\CartRepositoryInterface;
class Apply implements HttpPostActionInterface
{
public function __construct(private readonly RequestInterface $request, private readonly Validator $formKey, private readonly JsonFactory $jsonFactory, private readonly Session $checkoutSession, private readonly CustomerSession $customerSession, private readonly CartRepositoryInterface $quotes, private readonly BalanceManager $balances, private readonly ReservationManager $reservations, private readonly Config $config, private readonly CheckoutHelper $checkoutHelper) {}
public function execute()
{
$result = $this->jsonFactory->create();
try {
if (!$this->formKey->validate($this->request) || !$this->customerSession->isLoggedIn()) { throw new \Magento\Framework\Exception\LocalizedException(__('Please sign in to use reward points.')); }
$quote = $this->checkoutSession->getQuote(); $requested = max(0, (int)$this->request->getParam('points'));
$maximum = $this->config->maxCheckoutPoints((int)$quote->getStoreId()); $customerId = (int)$this->customerSession->getCustomerId(); $websiteId = (int)$quote->getStore()->getWebsiteId();
$balance = (int)$this->balances->getAccount($customerId, $websiteId)['balance'];
$quote->setData('reward_points_used', 0)->setTotalsCollectedFlag(false)->collectTotals();
$valueLimit = (int)floor(max(0.0, (float)$quote->getBaseGrandTotal()) * $this->config->redemptionRate((int)$quote->getStoreId()));
$points = min($requested, $maximum, $balance, $valueLimit);
$this->reservations->reserve($customerId, $websiteId, (int)$quote->getId(), $points + (int)$quote->getData('reward_product_points'));
$quote->setData('reward_points_used', $points)->setTotalsCollectedFlag(false)->collectTotals(); $this->quotes->save($quote);
return $result->setData([
'success' => true,
'points' => $points,
'balance' => $balance,
'reward_discount' => (float)$quote->getData('reward_discount_amount') > 0
? '-' . $this->checkoutHelper->formatPrice((float)$quote->getData('reward_discount_amount'))
: '',
'grand_total' => $this->checkoutHelper->formatPrice((float)$quote->getGrandTotal()),
'message' => $points > 0 ? (string)__('Reward points were applied.') : (string)__('Reward points were removed.'),
]);
} catch (\Throwable $e) { return $result->setHttpResponseCode(400)->setData(['success' => false, 'message' => $e->getMessage()]); }
}
}
@@ -0,0 +1,13 @@
<?php
declare(strict_types=1);
namespace Esun\Reward\Controller\Product;
use Magento\Framework\App\Action\HttpGetActionInterface;
use Magento\Framework\View\Result\PageFactory;
class Index implements HttpGetActionInterface
{
public function __construct(private readonly PageFactory $pages) {}
public function execute() { $page=$this->pages->create();$page->getConfig()->getTitle()->set(__('Redeem Products'));return $page; }
}
@@ -0,0 +1,41 @@
<?php
declare(strict_types=1);
namespace Esun\Reward\Controller\Product;
use Esun\Reward\Model\BalanceManager;
use Esun\Reward\Model\ReservationManager;
use Magento\Catalog\Api\ProductRepositoryInterface;
use Magento\Checkout\Model\Cart;
use Magento\Customer\Model\Session;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\Result\RedirectFactory;
use Magento\Framework\Data\Form\FormKey\Validator;
use Magento\Framework\DataObject;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Framework\Message\ManagerInterface;
class Redeem implements HttpPostActionInterface
{
public function __construct(private readonly RequestInterface $request,private readonly Validator $formKey,private readonly RedirectFactory $redirects,private readonly Session $session,private readonly ProductRepositoryInterface $products,private readonly Cart $cart,private readonly BalanceManager $balances,private readonly ReservationManager $reservations,private readonly Json $json,private readonly ManagerInterface $messages) {}
public function execute()
{
$redirect=$this->redirects->create()->setPath('reward/product/index');
try {
if(!$this->formKey->validate($this->request)||!$this->session->isLoggedIn()){throw new LocalizedException(__('Please sign in to redeem products.'));}
$product=$this->products->getById((int)$this->request->getParam('product_id'));$cost=(int)$product->getData('reward_points_cost');
if(!(bool)$product->getData('reward_redeemable')||$cost<=0||$product->getTypeId()!=='simple'){throw new LocalizedException(__('This product is not available for points redemption.'));}
$quote=$this->cart->getQuote();$customerId=(int)$this->session->getCustomerId();$existing=(int)$quote->getData('reward_product_points');$cash=(int)$quote->getData('reward_points_used');
if((int)$this->balances->getAccount($customerId,(int)$quote->getStore()->getWebsiteId())['balance']<$existing+$cash+$cost){throw new LocalizedException(__('You do not have enough points for this product.'));}
$product->addCustomOption('reward_redemption', '1');
$item=$this->cart->addProduct($product,new DataObject(['qty'=>1,'reward_redemption'=>1]));if(is_string($item)){throw new LocalizedException(__($item));}
$item->setCustomPrice(0)->setOriginalCustomPrice(0)->setData('reward_redemption',1)->setData('reward_points_cost',$cost);$item->getProduct()->setIsSuperMode(true);
$item->addOption(['code'=>'additional_options','value'=>$this->json->serialize([['label'=>(string)__('Points Redemption'),'value'=>(string)__('%1 points',$cost)]])]);
$quote->setData('reward_product_points',$existing+$cost);$this->reservations->reserve($customerId,(int)$quote->getStore()->getWebsiteId(),(int)$quote->getId(),$cash+$existing+$cost);$this->cart->save();
$this->messages->addSuccessMessage(__('The redemption product was added to your cart.'));
} catch(\Throwable $e){$this->messages->addErrorMessage($e->getMessage());return $redirect;}
return $redirect->setPath('checkout/cart');
}
}