init
This commit is contained in:
@@ -0,0 +1,20 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Block\Account;
|
||||
|
||||
use Esun\Reward\Model\BalanceManager;
|
||||
use Esun\Reward\Model\Config;
|
||||
use Esun\Reward\Model\TierResolver;
|
||||
use Magento\Customer\Model\Session;
|
||||
use Magento\Framework\View\Element\Template;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class Index extends Template
|
||||
{
|
||||
public function __construct(Template\Context $context, private readonly Session $session, private readonly StoreManagerInterface $stores, private readonly BalanceManager $balances, private readonly TierResolver $tiers, private readonly Config $config, array $data = []) { parent::__construct($context, $data); }
|
||||
public function getAccount(): array { return $this->balances->getAccount((int)$this->session->getCustomerId(), (int)$this->stores->getWebsite()->getId()); }
|
||||
public function getTier(): array { $account = $this->getAccount(); return $this->tiers->resolveEffective((string)$account['tier_code'], (float)$account['lifetime_spend_base'], (int)$this->stores->getStore()->getId()); }
|
||||
public function getTransactions(): array { return $this->balances->getTransactions((int)$this->session->getCustomerId(), 100); }
|
||||
public function getActivityName(string $type): string { return (string)$this->config->earningRule($type, (int)$this->stores->getStore()->getId())['name']; }
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Block\Adminhtml\Customer;
|
||||
|
||||
use Esun\Reward\Model\BalanceManager;
|
||||
use Esun\Reward\Model\TierResolver;
|
||||
use Magento\Backend\Block\Template;
|
||||
use Magento\Customer\Api\CustomerRepositoryInterface;
|
||||
use Esun\Reward\Model\Config;
|
||||
|
||||
class Reward extends Template
|
||||
{
|
||||
protected $_template = 'Esun_Reward::customer/reward.phtml';
|
||||
public function __construct(Template\Context $context, private readonly CustomerRepositoryInterface $customers, private readonly BalanceManager $balanceManager, private readonly TierResolver $tierResolver, private readonly Config $config, array $data = []) { parent::__construct($context, $data); }
|
||||
public function getCustomerId(): int { return (int)$this->getRequest()->getParam('id'); }
|
||||
public function getRewardData(): array
|
||||
{
|
||||
$customerId = $this->getCustomerId(); if ($customerId <= 0) { return []; }
|
||||
$customer = $this->customers->getById($customerId); $account = $this->balanceManager->getAccount($customerId, (int)$customer->getWebsiteId());
|
||||
$account['tier'] = $this->tierResolver->resolveEffective((string)$account['tier_code'], (float)$account['lifetime_spend_base']); return $account;
|
||||
}
|
||||
public function getTransactions(): array { return $this->getCustomerId() > 0 ? $this->balanceManager->getTransactions($this->getCustomerId(), 20) : []; }
|
||||
public function getAdjustUrl(): string { return $this->getUrl('esun_reward/customer/adjust'); }
|
||||
public function getSocialPoints(): int { return $this->config->socialPoints(); }
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Block\Adminhtml\System\Config\Form\Field;
|
||||
|
||||
use Magento\Framework\View\Element\Context;
|
||||
use Magento\Framework\View\Element\Html\Select;
|
||||
|
||||
class EarningEvent extends Select
|
||||
{
|
||||
public function __construct(Context $context, array $data = [])
|
||||
{
|
||||
parent::__construct($context, $data);
|
||||
$this->setOptions([
|
||||
['value' => 'registration', 'label' => __('Customer Registration')],
|
||||
['value' => 'first_shipping_address', 'label' => __('First Shipping Address')],
|
||||
['value' => 'order_earned', 'label' => __('Paid Order')],
|
||||
['value' => 'review_text', 'label' => __('Approved Text Review')],
|
||||
['value' => 'review_media', 'label' => __('Approved Review with Media')],
|
||||
['value' => 'social_share', 'label' => __('Social Share')],
|
||||
]);
|
||||
}
|
||||
|
||||
public function setInputName(string $value): self
|
||||
{
|
||||
return $this->setName($value);
|
||||
}
|
||||
|
||||
public function setInputId(string $value): self
|
||||
{
|
||||
return $this->setId($value);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Block\Adminhtml\System\Config\Form\Field;
|
||||
|
||||
use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray;
|
||||
use Magento\Framework\Data\Form\Element\AbstractElement;
|
||||
|
||||
class EarningRuleItems extends AbstractFieldArray
|
||||
{
|
||||
private ?EarningEvent $eventRenderer = null;
|
||||
|
||||
public function render(AbstractElement $element): string
|
||||
{
|
||||
$inheritRequired = $this->_isInheritCheckboxRequired($element);
|
||||
if ($element->getInherit() == 1 && $inheritRequired) {
|
||||
$element->setDisabled(true);
|
||||
}
|
||||
if ($element->getIsDisableInheritance()) {
|
||||
$element->setReadonly(true);
|
||||
}
|
||||
$html = '<td class="value" colspan="2">' . $this->_getElementHtml($element);
|
||||
if ($element->getComment()) {
|
||||
$html .= '<p class="note"><span>' . $element->getComment() . '</span></p>';
|
||||
}
|
||||
$html .= '</td>';
|
||||
if ($inheritRequired) {
|
||||
$html .= $this->_renderInheritCheckbox($element);
|
||||
}
|
||||
return $this->_decorateRowHtml($element, $html);
|
||||
}
|
||||
|
||||
protected function _prepareToRender(): void
|
||||
{
|
||||
$this->addColumn('code', [
|
||||
'label' => __('Trigger Event'),
|
||||
'renderer' => $this->getEventRenderer(),
|
||||
]);
|
||||
$this->addColumn('points', [
|
||||
'label' => __('Reward Points'),
|
||||
'class' => 'validate-number validate-zero-or-greater',
|
||||
'style' => 'width:130px',
|
||||
]);
|
||||
$this->addColumn('name', ['label' => __('Name'), 'style' => 'width:220px']);
|
||||
$this->addColumn('reason', ['label' => __('Reason'), 'style' => 'width:320px']);
|
||||
$this->_addAfter = false;
|
||||
$this->_addButtonLabel = __('Add Supported Rule');
|
||||
}
|
||||
|
||||
protected function _prepareArrayRow(\Magento\Framework\DataObject $row): void
|
||||
{
|
||||
$code = (string)$row->getData('code');
|
||||
$row->setData('option_extra_attrs', [
|
||||
'option_' . $this->getEventRenderer()->calcOptionHash($code) => 'selected="selected"',
|
||||
]);
|
||||
}
|
||||
|
||||
private function getEventRenderer(): EarningEvent
|
||||
{
|
||||
if ($this->eventRenderer === null) {
|
||||
$this->eventRenderer = $this->getLayout()->createBlock(
|
||||
EarningEvent::class,
|
||||
'',
|
||||
['data' => ['is_render_to_js_template' => true]]
|
||||
);
|
||||
}
|
||||
return $this->eventRenderer;
|
||||
}
|
||||
|
||||
public function getArrayRows(): array
|
||||
{
|
||||
$element = $this->getElement();
|
||||
if (!$element->getValue()) {
|
||||
$element->setValue([
|
||||
'_registration' => ['code' => 'registration', 'points' => '100', 'name' => 'Account Registration', 'reason' => 'Account registration reward'],
|
||||
'_first_address' => ['code' => 'first_shipping_address', 'points' => '100', 'name' => 'First Shipping Address', 'reason' => 'First saved shipping address reward'],
|
||||
'_order' => ['code' => 'order_earned', 'points' => '1', 'name' => 'Order Reward', 'reason' => 'Points earned from order %1'],
|
||||
'_review_text' => ['code' => 'review_text', 'points' => '20', 'name' => 'Product Review', 'reason' => 'Approved product review reward'],
|
||||
'_review_media' => ['code' => 'review_media', 'points' => '40', 'name' => 'Product Review with Media', 'reason' => 'Approved product review reward'],
|
||||
'_social' => ['code' => 'social_share', 'points' => '300', 'name' => 'Social Share', 'reason' => 'Social share reward'],
|
||||
]);
|
||||
}
|
||||
return parent::getArrayRows();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Block\Adminhtml\System\Config\Form\Field;
|
||||
|
||||
use Magento\Config\Block\System\Config\Form\Field\FieldArray\AbstractFieldArray;
|
||||
use Magento\Framework\Data\Form\Element\AbstractElement;
|
||||
|
||||
class TierItems extends AbstractFieldArray
|
||||
{
|
||||
public function render(AbstractElement $element): string
|
||||
{
|
||||
$isCheckboxRequired = $this->_isInheritCheckboxRequired($element);
|
||||
if ($element->getInherit() == 1 && $isCheckboxRequired) {
|
||||
$element->setDisabled(true);
|
||||
}
|
||||
if ($element->getIsDisableInheritance()) {
|
||||
$element->setReadonly(true);
|
||||
}
|
||||
|
||||
$html = '<td class="value" colspan="2">' . $this->_getElementHtml($element);
|
||||
if ($element->getComment()) {
|
||||
$html .= '<p class="note"><span>' . $element->getComment() . '</span></p>';
|
||||
}
|
||||
$html .= '</td>';
|
||||
if ($isCheckboxRequired) {
|
||||
$html .= $this->_renderInheritCheckbox($element);
|
||||
}
|
||||
|
||||
return $this->_decorateRowHtml($element, $html);
|
||||
}
|
||||
|
||||
protected function _prepareToRender(): void
|
||||
{
|
||||
$this->addColumn('label', ['label' => __('Tier Name'), 'style' => 'width:220px']);
|
||||
$this->addColumn('threshold', [
|
||||
'label' => __('Lifetime Spend Threshold'),
|
||||
'class' => 'validate-number validate-zero-or-greater',
|
||||
'style' => 'width:220px',
|
||||
]);
|
||||
$this->addColumn('multiplier', [
|
||||
'label' => __('Points Multiplier'),
|
||||
'class' => 'validate-number validate-greater-than-zero',
|
||||
'style' => 'width:160px',
|
||||
]);
|
||||
$this->_addAfter = false;
|
||||
$this->_addButtonLabel = __('Add Tier');
|
||||
}
|
||||
|
||||
public function getArrayRows(): array
|
||||
{
|
||||
$element = $this->getElement();
|
||||
if (!$element->getValue()) {
|
||||
$element->setValue([
|
||||
'_bronze' => ['label' => 'Bronze Maker', 'threshold' => '0', 'multiplier' => '1'],
|
||||
'_silver' => ['label' => 'Silver Maker', 'threshold' => '3000', 'multiplier' => '1.2'],
|
||||
'_gold' => ['label' => 'Gold Maker', 'threshold' => '7000', 'multiplier' => '1.5'],
|
||||
]);
|
||||
}
|
||||
|
||||
return parent::getArrayRows();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Block\Cart;
|
||||
|
||||
use Esun\Reward\Model\BalanceManager;
|
||||
use Esun\Reward\Model\Config;
|
||||
use Magento\Checkout\Model\Session;
|
||||
use Magento\Customer\Model\Session as CustomerSession;
|
||||
use Magento\Framework\View\Element\Template;
|
||||
|
||||
class Reward extends Template
|
||||
{
|
||||
public function __construct(Template\Context $context, private readonly Session $checkoutSession, private readonly CustomerSession $customerSession, private readonly BalanceManager $balances, private readonly Config $config, array $data = []) { parent::__construct($context, $data); }
|
||||
public function isLoggedIn(): bool { return $this->customerSession->isLoggedIn(); }
|
||||
public function getBalance(): int { $quote = $this->checkoutSession->getQuote(); return $this->isLoggedIn() ? (int)$this->balances->getAccount((int)$this->customerSession->getCustomerId(), (int)$quote->getStore()->getWebsiteId())['balance'] : 0; }
|
||||
public function getAppliedPoints(): int { return (int)$this->checkoutSession->getQuote()->getData('reward_points_used'); }
|
||||
public function getMaximum(): int { return $this->config->maxCheckoutPoints((int)$this->checkoutSession->getQuote()->getStoreId()); }
|
||||
public function getRate(): int { return $this->config->redemptionRate((int)$this->checkoutSession->getQuote()->getStoreId()); }
|
||||
public function getApplyUrl(): string { return $this->getUrl('reward/cart/apply'); }
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Block\Order;
|
||||
|
||||
use Magento\Framework\DataObject;
|
||||
use Magento\Framework\View\Element\Template;
|
||||
|
||||
class RewardTotals extends Template
|
||||
{
|
||||
public function initTotals(): self
|
||||
{
|
||||
$parent = $this->getParentBlock(); $source = $parent?->getSource();
|
||||
if ($parent && $source && (float)$source->getData('reward_discount_amount') > 0) {
|
||||
$parent->addTotal(new DataObject([
|
||||
'code' => 'reward_discount',
|
||||
'value' => -(float)$source->getData('reward_discount_amount'),
|
||||
'label' => __('Points Discount (%1 points)', (int)$source->getData('reward_points_used'))
|
||||
]), 'discount');
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Block\Product;
|
||||
|
||||
use Esun\Reward\Model\BalanceManager;
|
||||
use Magento\Catalog\Model\ResourceModel\Product\CollectionFactory;
|
||||
use Magento\Customer\Model\Session;
|
||||
use Magento\Framework\View\Element\Template;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
use Magento\Catalog\Helper\Image;
|
||||
|
||||
class ListProduct extends Template
|
||||
{
|
||||
public function __construct(Template\Context $context, private readonly CollectionFactory $collections, private readonly Session $session, private readonly StoreManagerInterface $stores, private readonly BalanceManager $balances, private readonly Image $image, array $data=[]) { parent::__construct($context,$data); }
|
||||
public function getProducts(): \Magento\Catalog\Model\ResourceModel\Product\Collection { return $this->collections->create()->addAttributeToSelect(['name','small_image','reward_points_cost','reward_redeemable'])->addAttributeToFilter('reward_redeemable',1)->addAttributeToFilter('reward_points_cost',['gt'=>0])->addAttributeToFilter('status',1)->setPageSize(48); }
|
||||
public function getBalance(): int { return $this->session->isLoggedIn()?(int)$this->balances->getAccount((int)$this->session->getCustomerId(),(int)$this->stores->getWebsite()->getId())['balance']:0; }
|
||||
public function isLoggedIn(): bool { return $this->session->isLoggedIn(); }
|
||||
public function getRedeemUrl(): string { return $this->getUrl('reward/product/redeem'); }
|
||||
public function getImageUrl(\Magento\Catalog\Model\Product $product): string { return $this->image->init($product, 'category_page_grid')->getUrl(); }
|
||||
}
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
email,member_tier,points
|
||||
customer@example.com,VIP III,1200
|
||||
customer2@example.com,Gold Maker,2500
|
||||
|
@@ -0,0 +1,179 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model;
|
||||
|
||||
use Magento\Framework\App\ResourceConnection;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
|
||||
class BalanceManager
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ResourceConnection $resource,
|
||||
private readonly Json $json,
|
||||
private readonly TierResolver $tierResolver
|
||||
) {}
|
||||
|
||||
public function getAccount(int $customerId, int $websiteId): array
|
||||
{
|
||||
$connection = $this->resource->getConnection();
|
||||
$table = $this->resource->getTableName('esun_reward_account');
|
||||
$rows = $connection->fetchAll(
|
||||
$connection->select()->from($table)->where('customer_id = ?', $customerId)->order('account_id ASC')
|
||||
);
|
||||
if (!$rows) {
|
||||
return ['customer_id' => $customerId, 'website_id' => $websiteId, 'balance' => 0, 'pending_balance' => 0, 'lifetime_earned' => 0, 'lifetime_spend_base' => 0, 'tier_code' => 'bronze'];
|
||||
}
|
||||
|
||||
$account = $rows[0];
|
||||
$account['website_id'] = $websiteId;
|
||||
$account['balance'] = array_sum(array_column($rows, 'balance'));
|
||||
$account['pending_balance'] = array_sum(array_column($rows, 'pending_balance'));
|
||||
$account['lifetime_earned'] = array_sum(array_column($rows, 'lifetime_earned'));
|
||||
$account['lifetime_spend_base'] = array_sum(array_column($rows, 'lifetime_spend_base'));
|
||||
return $account;
|
||||
}
|
||||
|
||||
public function change(int $customerId, int $websiteId, int $points, string $type, string $uniqueKey, array $context = []): bool
|
||||
{
|
||||
if ($customerId <= 0 || $points === 0 || $uniqueKey === '') { return false; }
|
||||
$connection = $this->resource->getConnection();
|
||||
$accountTable = $this->resource->getTableName('esun_reward_account');
|
||||
$transactionTable = $this->resource->getTableName('esun_reward_transaction');
|
||||
$connection->beginTransaction();
|
||||
try {
|
||||
if ($connection->fetchOne($connection->select()->from($transactionTable, ['transaction_id'])->where('unique_key = ?', $uniqueKey))) {
|
||||
$connection->rollBack(); return false;
|
||||
}
|
||||
$connection->insertOnDuplicate($accountTable, ['customer_id' => $customerId, 'website_id' => $websiteId], []);
|
||||
$accounts = $connection->fetchAll(
|
||||
$connection->select()->from($accountTable)->where('customer_id = ?', $customerId)->order('account_id ASC')->forUpdate(true)
|
||||
);
|
||||
$account = $accounts[0];
|
||||
$balance = (int)array_sum(array_column($accounts, 'balance'));
|
||||
if ($balance + $points < 0 && empty($context['allow_negative'])) { throw new LocalizedException(__('The customer does not have enough reward points.')); }
|
||||
$newBalance = $balance + $points;
|
||||
$connection->update($accountTable, [
|
||||
'balance' => $newBalance,
|
||||
'pending_balance' => (int)array_sum(array_column($accounts, 'pending_balance')),
|
||||
'lifetime_earned' => (int)array_sum(array_column($accounts, 'lifetime_earned')) + max(0, $points),
|
||||
'lifetime_spend_base' => (float)array_sum(array_column($accounts, 'lifetime_spend_base')),
|
||||
], ['account_id = ?' => (int)$account['account_id']]);
|
||||
if (count($accounts) > 1) {
|
||||
$connection->update($accountTable, [
|
||||
'balance' => 0, 'pending_balance' => 0, 'lifetime_earned' => 0, 'lifetime_spend_base' => 0,
|
||||
], ['customer_id = ?' => $customerId, 'account_id <> ?' => (int)$account['account_id']]);
|
||||
}
|
||||
$connection->insert($transactionTable, [
|
||||
'customer_id' => $customerId, 'website_id' => $websiteId, 'points_delta' => $points,
|
||||
'balance_after' => $newBalance, 'type' => $type, 'status' => $context['status'] ?? 'available',
|
||||
'reference_type' => $context['reference_type'] ?? null, 'reference_id' => isset($context['reference_id']) ? (string)$context['reference_id'] : null,
|
||||
'unique_key' => $uniqueKey, 'reason' => $context['reason'] ?? null,
|
||||
'admin_user_id' => $context['admin_user_id'] ?? null,
|
||||
'metadata' => empty($context['metadata']) ? null : $this->json->serialize($context['metadata']),
|
||||
]);
|
||||
$connection->commit(); return true;
|
||||
} catch (\Throwable $e) {
|
||||
if ($connection->getTransactionLevel() > 0) { $connection->rollBack(); }
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
public function addLifetimeSpend(int $customerId, int $websiteId, float $amount, ?int $storeId = null): void
|
||||
{
|
||||
$connection = $this->resource->getConnection(); $table = $this->resource->getTableName('esun_reward_account');
|
||||
$connection->beginTransaction();
|
||||
try {
|
||||
$connection->insertOnDuplicate($table, ['customer_id' => $customerId, 'website_id' => $websiteId], []);
|
||||
$accounts = $connection->fetchAll(
|
||||
$connection->select()->from($table)->where('customer_id = ?', $customerId)->order('account_id ASC')->forUpdate(true)
|
||||
);
|
||||
$account = $accounts[0];
|
||||
$spend = max(0.0, (float)array_sum(array_column($accounts, 'lifetime_spend_base')) + $amount);
|
||||
$tier = $this->tierResolver->resolveEffective(
|
||||
(string)($account['tier_code'] ?? ''),
|
||||
$spend,
|
||||
$storeId
|
||||
);
|
||||
$connection->update($table, [
|
||||
'balance' => (int)array_sum(array_column($accounts, 'balance')),
|
||||
'pending_balance' => (int)array_sum(array_column($accounts, 'pending_balance')),
|
||||
'lifetime_earned' => (int)array_sum(array_column($accounts, 'lifetime_earned')),
|
||||
'lifetime_spend_base' => $spend,
|
||||
'tier_code' => $tier['code'],
|
||||
], ['account_id = ?' => (int)$account['account_id']]);
|
||||
if (count($accounts) > 1) {
|
||||
$connection->update($table, [
|
||||
'balance' => 0, 'pending_balance' => 0, 'lifetime_earned' => 0, 'lifetime_spend_base' => 0,
|
||||
], ['customer_id = ?' => $customerId, 'account_id <> ?' => (int)$account['account_id']]);
|
||||
}
|
||||
$connection->commit();
|
||||
} catch (\Throwable $e) { if ($connection->getTransactionLevel() > 0) { $connection->rollBack(); } throw $e; }
|
||||
}
|
||||
|
||||
public function importLegacySnapshot(
|
||||
int $customerId,
|
||||
int $websiteId,
|
||||
int $targetBalance,
|
||||
string $targetTierCode,
|
||||
string $batchId,
|
||||
array $metadata = []
|
||||
): bool {
|
||||
if ($customerId <= 0 || $websiteId <= 0 || $targetBalance < 0
|
||||
|| !in_array($targetTierCode, ['bronze', 'silver', 'gold'], true) || trim($batchId) === '') {
|
||||
throw new LocalizedException(__('Invalid reward migration snapshot.'));
|
||||
}
|
||||
$connection = $this->resource->getConnection();
|
||||
$accountTable = $this->resource->getTableName('esun_reward_account');
|
||||
$transactionTable = $this->resource->getTableName('esun_reward_transaction');
|
||||
$uniqueKey = sprintf('migration:%s:%d:%d', hash('sha256', trim($batchId)), $customerId, $websiteId);
|
||||
$connection->beginTransaction();
|
||||
try {
|
||||
if ($connection->fetchOne($connection->select()->from($transactionTable, ['transaction_id'])->where('unique_key = ?', $uniqueKey))) {
|
||||
$connection->rollBack();
|
||||
return false;
|
||||
}
|
||||
$connection->insertOnDuplicate($accountTable, ['customer_id' => $customerId, 'website_id' => $websiteId], []);
|
||||
$account = $connection->fetchRow($connection->select()->from($accountTable)
|
||||
->where('customer_id = ?', $customerId)->where('website_id = ?', $websiteId)->forUpdate(true));
|
||||
$currentBalance = (int)($account['balance'] ?? 0);
|
||||
$delta = $targetBalance - $currentBalance;
|
||||
$connection->update($accountTable, [
|
||||
'balance' => $targetBalance,
|
||||
'lifetime_earned' => max((int)($account['lifetime_earned'] ?? 0), $targetBalance),
|
||||
'tier_code' => $targetTierCode,
|
||||
], ['account_id = ?' => (int)$account['account_id']]);
|
||||
$connection->insert($transactionTable, [
|
||||
'customer_id' => $customerId, 'website_id' => $websiteId, 'points_delta' => $delta,
|
||||
'balance_after' => $targetBalance, 'type' => 'migration', 'status' => 'available',
|
||||
'reference_type' => 'migration', 'reference_id' => substr($batchId, 0, 64),
|
||||
'unique_key' => $uniqueKey, 'reason' => 'Legacy reward migration',
|
||||
'metadata' => $this->json->serialize($metadata + [
|
||||
'tier_code' => $targetTierCode,
|
||||
]),
|
||||
]);
|
||||
$connection->commit();
|
||||
return true;
|
||||
} catch (\Throwable $e) {
|
||||
if ($connection->getTransactionLevel() > 0) { $connection->rollBack(); }
|
||||
throw $e;
|
||||
}
|
||||
}
|
||||
|
||||
public function getTransactions(int $customerId, int $limit = 50): array
|
||||
{
|
||||
$connection = $this->resource->getConnection();
|
||||
$rows = $connection->fetchAll(
|
||||
$connection->select()->from($this->resource->getTableName('esun_reward_transaction'))
|
||||
->where('customer_id = ?', $customerId)->order('transaction_id ASC')
|
||||
);
|
||||
$balance = 0;
|
||||
foreach ($rows as &$row) {
|
||||
$balance += (int)$row['points_delta'];
|
||||
$row['balance_after'] = $balance;
|
||||
}
|
||||
unset($row);
|
||||
return array_slice(array_reverse($rows), 0, max(1, min(200, $limit)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model;
|
||||
|
||||
use Magento\Checkout\Model\Cart as CheckoutCart;
|
||||
use Magento\Checkout\Model\ConfigProviderInterface;
|
||||
use Magento\Customer\Helper\Session\CurrentCustomer;
|
||||
|
||||
class CheckoutConfigProvider implements ConfigProviderInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CheckoutCart $checkoutCart,
|
||||
private readonly CurrentCustomer $currentCustomer,
|
||||
private readonly BalanceManager $balances,
|
||||
private readonly Config $config
|
||||
) {}
|
||||
|
||||
public function getConfig(): array
|
||||
{
|
||||
$quote = $this->checkoutCart->getQuote();
|
||||
$customerId = (int)$this->currentCustomer->getCustomerId()
|
||||
?: (int)$quote->getCustomerId();
|
||||
$balance = $customerId > 0
|
||||
? (int)$this->balances->getAccount(
|
||||
$customerId,
|
||||
(int)$quote->getStore()->getWebsiteId()
|
||||
)['balance']
|
||||
: 0;
|
||||
|
||||
return ['esunReward' => [
|
||||
'logged_in' => $customerId > 0,
|
||||
'balance' => $balance,
|
||||
'applied_points' => (int)$quote->getData('reward_points_used'),
|
||||
'maximum' => $this->config->maxCheckoutPoints((int)$quote->getStoreId()),
|
||||
'rate' => $this->config->redemptionRate((int)$quote->getStoreId()),
|
||||
]];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model;
|
||||
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use Magento\Store\Model\ScopeInterface;
|
||||
|
||||
class Config
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ScopeConfigInterface $scopeConfig,
|
||||
private readonly Json $serializer
|
||||
) {}
|
||||
|
||||
public function isEnabled(?int $storeId = null): bool { return $this->flag('general/enabled', $storeId); }
|
||||
public function registrationPoints(?int $storeId = null): int { return (int)$this->earningRule('registration', $storeId)['points']; }
|
||||
public function firstAddressPoints(?int $storeId = null): int { return (int)$this->earningRule('first_shipping_address', $storeId)['points']; }
|
||||
public function orderRate(?int $storeId = null): float { return (float)$this->earningRule('order_earned', $storeId)['points']; }
|
||||
public function reviewTextPoints(?int $storeId = null): int { return (int)$this->earningRule('review_text', $storeId)['points']; }
|
||||
public function reviewMediaPoints(?int $storeId = null): int { return (int)$this->earningRule('review_media', $storeId)['points']; }
|
||||
public function socialPoints(?int $storeId = null): int { return (int)$this->earningRule('social_share', $storeId)['points']; }
|
||||
public function redemptionRate(?int $storeId = null): int { return max(1, $this->int('spending/points_per_dollar', $storeId)); }
|
||||
public function maxCheckoutPoints(?int $storeId = null): int { return $this->int('spending/max_checkout_points', $storeId); }
|
||||
public function reviewEligibility(?int $storeId = null): string { return (string)$this->value('review/eligibility', $storeId); }
|
||||
public function silverThreshold(?int $storeId = null): float { return $this->float('tiers/silver_threshold', $storeId); }
|
||||
public function silverMultiplier(?int $storeId = null): float { return $this->float('tiers/silver_multiplier', $storeId); }
|
||||
public function goldThreshold(?int $storeId = null): float { return $this->float('tiers/gold_threshold', $storeId); }
|
||||
public function goldMultiplier(?int $storeId = null): float { return $this->float('tiers/gold_multiplier', $storeId); }
|
||||
|
||||
/** @return array{code: string, points: float, name: string, reason: string} */
|
||||
public function earningRule(string $code, ?int $storeId = null): array
|
||||
{
|
||||
$rules = $this->earningRules($storeId);
|
||||
return $rules[$code] ?? ['code' => $code, 'points' => 0.0, 'name' => ucwords(str_replace('_', ' ', $code)), 'reason' => ''];
|
||||
}
|
||||
|
||||
/** @return array<string, array{code: string, points: float, name: string, reason: string}> */
|
||||
public function earningRules(?int $storeId = null): array
|
||||
{
|
||||
$defaults = [
|
||||
'registration' => ['points' => (float)$this->int('earning/registration_points', $storeId), 'name' => 'Account Registration', 'reason' => 'Account registration reward'],
|
||||
'first_shipping_address' => ['points' => (float)$this->int('earning/first_address_points', $storeId), 'name' => 'First Shipping Address', 'reason' => 'First saved shipping address reward'],
|
||||
'order_earned' => ['points' => $this->float('earning/points_per_dollar', $storeId), 'name' => 'Order Reward', 'reason' => 'Points earned from order %1'],
|
||||
'review_text' => ['points' => (float)$this->int('earning/review_text_points', $storeId), 'name' => 'Product Review', 'reason' => 'Approved product review reward'],
|
||||
'review_media' => ['points' => (float)$this->int('earning/review_media_points', $storeId), 'name' => 'Product Review with Media', 'reason' => 'Approved product review reward'],
|
||||
'social_share' => ['points' => (float)$this->int('earning/social_share_points', $storeId), 'name' => 'Social Share', 'reason' => 'Social share reward'],
|
||||
];
|
||||
foreach ($defaults as $code => &$rule) {
|
||||
$rule['code'] = $code;
|
||||
}
|
||||
unset($rule);
|
||||
|
||||
$value = $this->value('earning/items', $storeId);
|
||||
try {
|
||||
$items = is_array($value) ? $value : (empty($value) ? [] : $this->serializer->unserialize((string)$value));
|
||||
} catch (\InvalidArgumentException) {
|
||||
$items = [];
|
||||
}
|
||||
if (!is_array($items) || !$items) {
|
||||
return $defaults;
|
||||
}
|
||||
|
||||
$rules = [];
|
||||
foreach ($items as $item) {
|
||||
if (!is_array($item)) {
|
||||
continue;
|
||||
}
|
||||
$code = strtolower(trim((string)($item['code'] ?? '')));
|
||||
$name = trim((string)($item['name'] ?? ''));
|
||||
if ($code === '' || $name === '') {
|
||||
continue;
|
||||
}
|
||||
$rules[$code] = [
|
||||
'code' => $code,
|
||||
'points' => max(0.0, (float)($item['points'] ?? 0)),
|
||||
'name' => $name,
|
||||
'reason' => trim((string)($item['reason'] ?? '')),
|
||||
];
|
||||
}
|
||||
return $rules ?: $defaults;
|
||||
}
|
||||
|
||||
/** @return array<int, array{code: string, label: string, threshold: float, multiplier: float}> */
|
||||
public function tiers(?int $storeId = null): array
|
||||
{
|
||||
$value = $this->value('tiers/items', $storeId);
|
||||
try {
|
||||
$items = is_array($value) ? $value : (empty($value) ? [] : $this->serializer->unserialize((string)$value));
|
||||
} catch (\InvalidArgumentException) {
|
||||
$items = [];
|
||||
}
|
||||
if (!is_array($items)) {
|
||||
$items = [];
|
||||
}
|
||||
|
||||
$tiers = [];
|
||||
foreach ($items as $item) {
|
||||
if (!is_array($item)) {
|
||||
continue;
|
||||
}
|
||||
$label = trim((string)($item['label'] ?? ''));
|
||||
$threshold = max(0.0, (float)($item['threshold'] ?? 0));
|
||||
$multiplier = (float)($item['multiplier'] ?? 0);
|
||||
if ($label === '' || $multiplier <= 0) {
|
||||
continue;
|
||||
}
|
||||
$tiers[] = [
|
||||
'code' => strtolower((string)preg_replace('/[^a-z0-9]+/i', '_', $label)),
|
||||
'label' => $label,
|
||||
'threshold' => $threshold,
|
||||
'multiplier' => $multiplier,
|
||||
];
|
||||
}
|
||||
|
||||
if (!$tiers) {
|
||||
$tiers = [
|
||||
['code' => 'bronze', 'label' => 'Bronze Maker', 'threshold' => 0.0, 'multiplier' => 1.0],
|
||||
['code' => 'silver', 'label' => 'Silver Maker', 'threshold' => $this->silverThreshold($storeId), 'multiplier' => $this->silverMultiplier($storeId)],
|
||||
['code' => 'gold', 'label' => 'Gold Maker', 'threshold' => $this->goldThreshold($storeId), 'multiplier' => $this->goldMultiplier($storeId)],
|
||||
];
|
||||
}
|
||||
|
||||
usort($tiers, static fn(array $left, array $right): int => $left['threshold'] <=> $right['threshold']);
|
||||
return $tiers;
|
||||
}
|
||||
|
||||
private function value(string $path, ?int $storeId): mixed { return $this->scopeConfig->getValue('esun_reward/' . $path, ScopeInterface::SCOPE_STORE, $storeId); }
|
||||
private function int(string $path, ?int $storeId): int { return max(0, (int)$this->value($path, $storeId)); }
|
||||
private function float(string $path, ?int $storeId): float { return max(0.0, (float)$this->value($path, $storeId)); }
|
||||
private function flag(string $path, ?int $storeId): bool { return $this->scopeConfig->isSetFlag('esun_reward/' . $path, ScopeInterface::SCOPE_STORE, $storeId); }
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model\Config\Backend;
|
||||
|
||||
use Magento\Config\Model\Config\Backend\Serialized\ArraySerialized;
|
||||
use Magento\Config\Model\ResourceModel\Config\Data as ConfigResource;
|
||||
use Magento\Config\Model\ResourceModel\Config\Data\Collection as ConfigCollection;
|
||||
|
||||
class EarningRuleItems extends ArraySerialized
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_setResourceModel(ConfigResource::class, ConfigCollection::class);
|
||||
}
|
||||
|
||||
public function beforeSave()
|
||||
{
|
||||
$items = [];
|
||||
$allowedCodes = [
|
||||
'registration', 'first_shipping_address', 'order_earned',
|
||||
'review_text', 'review_media', 'social_share',
|
||||
];
|
||||
$value = $this->getValue();
|
||||
if (is_array($value)) {
|
||||
unset($value['__empty']);
|
||||
foreach ($value as $row) {
|
||||
if (!is_array($row)) {
|
||||
continue;
|
||||
}
|
||||
$code = strtolower(trim((string)($row['code'] ?? '')));
|
||||
$points = max(0.0, (float)($row['points'] ?? 0));
|
||||
$name = trim((string)($row['name'] ?? ''));
|
||||
$reason = trim((string)($row['reason'] ?? ''));
|
||||
if (!in_array($code, $allowedCodes, true) || $name === '') {
|
||||
continue;
|
||||
}
|
||||
$items[$code] = ['code' => $code, 'points' => $points, 'name' => $name, 'reason' => $reason];
|
||||
}
|
||||
}
|
||||
$this->setValue(array_values($items));
|
||||
return parent::beforeSave();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model\Config\Backend;
|
||||
|
||||
use Magento\Config\Model\Config\Backend\Serialized\ArraySerialized;
|
||||
use Magento\Config\Model\ResourceModel\Config\Data as ConfigResource;
|
||||
use Magento\Config\Model\ResourceModel\Config\Data\Collection as ConfigCollection;
|
||||
|
||||
class TierItems extends ArraySerialized
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_setResourceModel(ConfigResource::class, ConfigCollection::class);
|
||||
}
|
||||
|
||||
public function beforeSave()
|
||||
{
|
||||
$items = [];
|
||||
$value = $this->getValue();
|
||||
if (is_array($value)) {
|
||||
unset($value['__empty']);
|
||||
foreach ($value as $row) {
|
||||
if (!is_array($row)) {
|
||||
continue;
|
||||
}
|
||||
$label = trim((string)($row['label'] ?? ''));
|
||||
$threshold = max(0.0, (float)($row['threshold'] ?? 0));
|
||||
$multiplier = (float)($row['multiplier'] ?? 0);
|
||||
if ($label === '' || $multiplier <= 0) {
|
||||
continue;
|
||||
}
|
||||
$items[] = ['label' => $label, 'threshold' => $threshold, 'multiplier' => $multiplier];
|
||||
}
|
||||
}
|
||||
|
||||
usort($items, static fn(array $left, array $right): int => $left['threshold'] <=> $right['threshold']);
|
||||
$this->setValue($items);
|
||||
|
||||
return parent::beforeSave();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model\Config\Source;
|
||||
|
||||
use Magento\Framework\Data\OptionSourceInterface;
|
||||
|
||||
class ReviewEligibility implements OptionSourceInterface
|
||||
{
|
||||
public function toOptionArray(): array
|
||||
{
|
||||
return [
|
||||
['value' => 'payment_success', 'label' => __('Payment Successful')],
|
||||
['value' => 'order_complete', 'label' => __('Order Complete')],
|
||||
['value' => 'confirmed_receipt', 'label' => __('Customer Confirmed Receipt')],
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model\Import;
|
||||
|
||||
use Esun\Reward\Model\BalanceManager;
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
use Magento\Framework\App\ResourceConnection;
|
||||
use Magento\Framework\Serialize\Serializer\Json;
|
||||
use Magento\Framework\Stdlib\StringUtils;
|
||||
use Magento\ImportExport\Model\Import as ImportModel;
|
||||
use Magento\ImportExport\Model\Import\AbstractEntity;
|
||||
use Magento\ImportExport\Model\Import\ErrorProcessing\ProcessingErrorAggregatorInterface;
|
||||
use Magento\ImportExport\Model\ImportFactory;
|
||||
use Magento\ImportExport\Model\ResourceModel\Helper;
|
||||
|
||||
class Reward extends AbstractEntity
|
||||
{
|
||||
public const ENTITY_CODE = 'esun_reward';
|
||||
public const COL_EMAIL = 'email';
|
||||
public const COL_TIER = 'member_tier';
|
||||
public const COL_POINTS = 'points';
|
||||
private const ERROR_EMAIL = 'rewardInvalidEmail';
|
||||
private const ERROR_TIER = 'rewardInvalidTier';
|
||||
private const ERROR_POINTS = 'rewardInvalidPoints';
|
||||
private const ERROR_NOT_FOUND = 'rewardCustomerNotFound';
|
||||
private const ERROR_MULTIPLE = 'rewardCustomerMultipleWebsites';
|
||||
private const ERROR_DUPLICATE = 'rewardDuplicateEmail';
|
||||
private const TIER_MAP = [
|
||||
'VIP I' => 'bronze', 'BRONZE MAKER' => 'bronze',
|
||||
'VIP II' => 'silver', 'SILVER MAKER' => 'silver',
|
||||
'VIP III' => 'gold', 'GOLD MAKER' => 'gold',
|
||||
];
|
||||
|
||||
protected $needColumnCheck = true;
|
||||
protected $validColumnNames = [self::COL_EMAIL, self::COL_TIER, self::COL_POINTS];
|
||||
protected $_availableBehaviors = [ImportModel::BEHAVIOR_APPEND];
|
||||
protected $masterAttributeCode = self::COL_EMAIL;
|
||||
private array $seenEmails = [];
|
||||
|
||||
public function __construct(
|
||||
StringUtils $string,
|
||||
ScopeConfigInterface $scopeConfig,
|
||||
ImportFactory $importFactory,
|
||||
Helper $resourceHelper,
|
||||
ResourceConnection $resource,
|
||||
ProcessingErrorAggregatorInterface $errorAggregator,
|
||||
private readonly ResourceConnection $rewardResource,
|
||||
private readonly BalanceManager $balances,
|
||||
array $data = [],
|
||||
?Json $serializer = null
|
||||
) {
|
||||
parent::__construct($string, $scopeConfig, $importFactory, $resourceHelper, $resource, $errorAggregator, $data, $serializer);
|
||||
$this->addMessageTemplate(self::ERROR_EMAIL, 'Email format is invalid');
|
||||
$this->addMessageTemplate(self::ERROR_TIER, 'Member tier is invalid; use VIP I/II/III or Bronze/Silver/Gold Maker');
|
||||
$this->addMessageTemplate(self::ERROR_POINTS, 'Points must be a non-negative integer');
|
||||
$this->addMessageTemplate(self::ERROR_NOT_FOUND, '未找到该邮箱对应的客户');
|
||||
$this->addMessageTemplate(self::ERROR_MULTIPLE, '该邮箱存在于多个 Website,请人工确认归属');
|
||||
$this->addMessageTemplate(self::ERROR_DUPLICATE, 'CSV 中邮箱重复');
|
||||
}
|
||||
|
||||
public function getEntityTypeCode(): string { return self::ENTITY_CODE; }
|
||||
|
||||
public function validateRow(array $rowData, $rowNumber): bool
|
||||
{
|
||||
if (isset($this->_validatedRows[$rowNumber])) {
|
||||
return !$this->getErrorAggregator()->isRowInvalid($rowNumber);
|
||||
}
|
||||
$this->_validatedRows[$rowNumber] = true;
|
||||
$email = strtolower(trim((string)($rowData[self::COL_EMAIL] ?? '')));
|
||||
$tier = $this->normalizeTier((string)($rowData[self::COL_TIER] ?? ''));
|
||||
$points = trim((string)($rowData[self::COL_POINTS] ?? ''));
|
||||
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $this->addRowError(self::ERROR_EMAIL, $rowNumber, self::COL_EMAIL); }
|
||||
if ($tier === null) { $this->addRowError(self::ERROR_TIER, $rowNumber, self::COL_TIER); }
|
||||
if (!preg_match('/^\d+$/', $points)) { $this->addRowError(self::ERROR_POINTS, $rowNumber, self::COL_POINTS); }
|
||||
if ($email !== '') {
|
||||
if (isset($this->seenEmails[$email])) { $this->addRowError(self::ERROR_DUPLICATE, $rowNumber, self::COL_EMAIL); }
|
||||
$this->seenEmails[$email] = true;
|
||||
$count = count($this->findCustomers($email));
|
||||
if ($count === 0) { $this->addRowError(self::ERROR_NOT_FOUND, $rowNumber, self::COL_EMAIL); }
|
||||
if ($count > 1) { $this->addRowError(self::ERROR_MULTIPLE, $rowNumber, self::COL_EMAIL); }
|
||||
}
|
||||
return !$this->getErrorAggregator()->isRowInvalid($rowNumber);
|
||||
}
|
||||
|
||||
protected function _importData()
|
||||
{
|
||||
$batchId = 'admin-import-' . gmdate('YmdHis') . '-' . bin2hex(random_bytes(4));
|
||||
while ($bunch = $this->_dataSourceModel->getNextUniqueBunch($this->getIds())) {
|
||||
foreach ($bunch as $rowNumber => $rowData) {
|
||||
if (!$this->validateRow($rowData, $rowNumber)) { continue; }
|
||||
$email = strtolower(trim((string)$rowData[self::COL_EMAIL]));
|
||||
$customers = $this->findCustomers($email);
|
||||
$customer = reset($customers);
|
||||
$this->balances->importLegacySnapshot(
|
||||
(int)$customer['entity_id'], (int)$customer['website_id'], (int)$rowData[self::COL_POINTS],
|
||||
(string)$this->normalizeTier((string)$rowData[self::COL_TIER]), $batchId,
|
||||
['source' => 'admin_import', 'source_row' => $rowNumber, 'source_email' => $email]
|
||||
);
|
||||
$this->countItemsUpdated++;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private function normalizeTier(string $value): ?string
|
||||
{
|
||||
$label = strtoupper((string)preg_replace('/\s+/', ' ', trim($value)));
|
||||
return self::TIER_MAP[$label] ?? null;
|
||||
}
|
||||
|
||||
/** @return array<int,array{entity_id:string,website_id:string}> */
|
||||
private function findCustomers(string $email): array
|
||||
{
|
||||
$table = $this->rewardResource->getTableName('customer_entity');
|
||||
return $this->rewardResource->getConnection()->fetchAll(
|
||||
$this->rewardResource->getConnection()->select()
|
||||
->from($table, ['entity_id', 'website_id'])
|
||||
->where('LOWER(email) = ?', strtolower(trim($email)))
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model;
|
||||
|
||||
use Magento\Framework\App\ResourceConnection;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
|
||||
class ReservationManager
|
||||
{
|
||||
public function __construct(private readonly ResourceConnection $resource, private readonly BalanceManager $balances) {}
|
||||
public function reserve(int $customerId, int $websiteId, int $quoteId, int $points): void
|
||||
{
|
||||
$connection = $this->resource->getConnection(); $table = $this->resource->getTableName('esun_reward_reservation');
|
||||
$connection->beginTransaction();
|
||||
try {
|
||||
$accountTable = $this->resource->getTableName('esun_reward_account');
|
||||
$connection->insertOnDuplicate($accountTable, ['customer_id' => $customerId, 'website_id' => $websiteId], []);
|
||||
$account = $connection->fetchRow($connection->select()->from($accountTable)->where('customer_id = ?', $customerId)->where('website_id = ?', $websiteId)->forUpdate(true));
|
||||
$otherReserved = (int)$connection->fetchOne($connection->select()->from($table, ['SUM(points)'])->where('customer_id = ?', $customerId)->where('status = ?', 'active')->where('quote_id != ?', $quoteId)->where('expires_at IS NULL OR expires_at > ?', date('Y-m-d H:i:s')));
|
||||
if ($points > max(0, (int)$account['balance'] - $otherReserved)) { throw new LocalizedException(__('You do not have enough available reward points.')); }
|
||||
if ($points <= 0) { $connection->delete($table, ['quote_id = ?' => $quoteId]); }
|
||||
else { $connection->insertOnDuplicate($table, ['customer_id' => $customerId, 'quote_id' => $quoteId, 'points' => $points, 'status' => 'active', 'expires_at' => date('Y-m-d H:i:s', time() + 86400)], ['customer_id', 'points', 'status', 'expires_at']); }
|
||||
$connection->commit();
|
||||
} catch (\Throwable $e) { if ($connection->getTransactionLevel() > 0) { $connection->rollBack(); } throw $e; }
|
||||
}
|
||||
public function markUsed(int $quoteId): void { $this->resource->getConnection()->update($this->resource->getTableName('esun_reward_reservation'), ['status' => 'used'], ['quote_id = ?' => $quoteId]); }
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model;
|
||||
|
||||
class TierResolver
|
||||
{
|
||||
public function __construct(private readonly Config $config) {}
|
||||
|
||||
public function resolve(float $lifetimeSpend, ?int $storeId = null): array
|
||||
{
|
||||
$tiers = $this->config->tiers($storeId);
|
||||
$current = $tiers[0];
|
||||
$nextThreshold = null;
|
||||
|
||||
foreach ($tiers as $tier) {
|
||||
if ($lifetimeSpend >= $tier['threshold']) {
|
||||
$current = $tier;
|
||||
continue;
|
||||
}
|
||||
$nextThreshold = $tier['threshold'];
|
||||
break;
|
||||
}
|
||||
|
||||
return [
|
||||
'code' => $current['code'],
|
||||
'label' => $current['label'],
|
||||
'multiplier' => $current['multiplier'],
|
||||
'next_threshold' => $nextThreshold,
|
||||
];
|
||||
}
|
||||
|
||||
public function resolveEffective(string $savedTierCode, float $lifetimeSpend, ?int $storeId = null): array
|
||||
{
|
||||
$tiers = $this->config->tiers($storeId);
|
||||
$computed = $this->resolve($lifetimeSpend, $storeId);
|
||||
$byCode = [];
|
||||
foreach ($tiers as $position => $tier) {
|
||||
$byCode[$tier['code']] = ['position' => $position, 'tier' => $tier];
|
||||
}
|
||||
if (!isset($byCode[$savedTierCode])) {
|
||||
return $computed;
|
||||
}
|
||||
$saved = $byCode[$savedTierCode];
|
||||
$computedPosition = $byCode[$computed['code']]['position'] ?? 0;
|
||||
if ($saved['position'] <= $computedPosition) {
|
||||
return $computed;
|
||||
}
|
||||
$nextThreshold = $tiers[$saved['position'] + 1]['threshold'] ?? null;
|
||||
return [
|
||||
'code' => $saved['tier']['code'],
|
||||
'label' => $saved['tier']['label'],
|
||||
'multiplier' => $saved['tier']['multiplier'],
|
||||
'next_threshold' => $nextThreshold,
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Model\Total\Quote;
|
||||
|
||||
use Esun\Reward\Model\Config;
|
||||
use Magento\Quote\Api\Data\ShippingAssignmentInterface;
|
||||
use Magento\Quote\Model\Quote;
|
||||
use Magento\Quote\Model\Quote\Address\Total;
|
||||
use Magento\Quote\Model\Quote\Address\Total\AbstractTotal;
|
||||
|
||||
class RewardDiscount extends AbstractTotal
|
||||
{
|
||||
protected $_code = 'reward_discount';
|
||||
public function __construct(private readonly Config $config) {}
|
||||
public function collect(Quote $quote, ShippingAssignmentInterface $shippingAssignment, Total $total): self
|
||||
{
|
||||
parent::collect($quote, $shippingAssignment, $total);
|
||||
|
||||
// A physical quote is collected once for shipping and again for its
|
||||
// empty billing assignment. Do not let the empty pass erase the
|
||||
// reward amount calculated for the shipping address.
|
||||
if (!$shippingAssignment->getItems()) {
|
||||
return $this;
|
||||
}
|
||||
|
||||
$points = (int)$quote->getData('reward_points_used');
|
||||
if ($points <= 0 || !$quote->getCustomerId() || !$this->config->isEnabled((int)$quote->getStoreId())) {
|
||||
$quote->setData('reward_discount_amount', 0)->setData('base_reward_discount_amount', 0); return $this;
|
||||
}
|
||||
$baseRequested = $points / $this->config->redemptionRate((int)$quote->getStoreId());
|
||||
$baseMaximum = max(0.0, array_sum($total->getAllBaseTotalAmounts()));
|
||||
$baseDiscount = min($baseRequested, $baseMaximum);
|
||||
$discount = (float)$quote->getStore()->getBaseCurrency()->convert($baseDiscount, $quote->getStore()->getCurrentCurrency());
|
||||
$total->setBaseTotalAmount($this->getCode(), -$baseDiscount); $total->setTotalAmount($this->getCode(), -$discount);
|
||||
$quote->setData('base_reward_discount_amount', $baseDiscount)->setData('reward_discount_amount', $discount);
|
||||
return $this;
|
||||
}
|
||||
public function fetch(Quote $quote, Total $total): array
|
||||
{
|
||||
$amount = (float)$quote->getData('reward_discount_amount');
|
||||
$points = (int)$quote->getData('reward_points_used');
|
||||
return $amount > 0 ? [
|
||||
'code' => $this->getCode(),
|
||||
'title' => __('Points Discount (%1 points)', $points),
|
||||
'value' => -$amount
|
||||
] : [];
|
||||
}
|
||||
public function getLabel(): string { return (string)__('Points Discount'); }
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Observer;
|
||||
|
||||
use Esun\Reward\Model\BalanceManager;
|
||||
use Esun\Reward\Model\Config;
|
||||
use Magento\Framework\App\ResourceConnection;
|
||||
use Magento\Framework\Event\Observer;
|
||||
use Magento\Framework\Event\ObserverInterface;
|
||||
use Magento\Review\Model\Review;
|
||||
use Magento\Customer\Api\CustomerRepositoryInterface;
|
||||
|
||||
class AwardApprovedReviewPoints implements ObserverInterface
|
||||
{
|
||||
public function __construct(private readonly BalanceManager $balanceManager, private readonly Config $config, private readonly ResourceConnection $resource, private readonly CustomerRepositoryInterface $customers) {}
|
||||
public function execute(Observer $observer): void
|
||||
{
|
||||
/** @var Review|null $review */ $review = $observer->getEvent()->getDataObject();
|
||||
$customerId = (int)($review?->getCustomerId() ?? 0);
|
||||
if (!$review || (int)$review->getStatusId() !== Review::STATUS_APPROVED || $customerId <= 0 || !$this->config->isEnabled((int)$review->getStoreId())) { return; }
|
||||
$connection = $this->resource->getConnection();
|
||||
$purchase = $connection->fetchRow($connection->select()->from($this->resource->getTableName('esun_review_purchase'))->where('review_id = ?', (int)$review->getId())->limit(1));
|
||||
if (!$purchase) { return; }
|
||||
$hasMedia = (bool)$connection->fetchOne($connection->select()->from($this->resource->getTableName('esun_review_image'), ['image_id'])->where('review_id = ?', (int)$review->getId())->where('status = ?', 1)->limit(1));
|
||||
$type = $hasMedia ? 'review_media' : 'review_text';
|
||||
$rule = $this->config->earningRule($type, (int)$review->getStoreId());
|
||||
$points = (int)$rule['points'];
|
||||
$websiteId = (int)$this->customers->getById($customerId)->getWebsiteId();
|
||||
$this->balanceManager->change($customerId, $websiteId, $points, $type, 'review_reward:' . (int)$review->getId(), [
|
||||
'reference_type' => 'review', 'reference_id' => (int)$review->getId(), 'reason' => (string)__($rule['reason']),
|
||||
'metadata' => ['product_id' => (int)$review->getEntityPkValue(), 'order_id' => (int)$purchase['order_id'], 'order_item_id' => (int)$purchase['order_item_id'], 'has_media' => $hasMedia]
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Observer;
|
||||
|
||||
use Esun\Reward\Model\BalanceManager;
|
||||
use Esun\Reward\Model\Config;
|
||||
use Magento\Framework\App\ResourceConnection;
|
||||
use Magento\Framework\Event\Observer;
|
||||
use Magento\Framework\Event\ObserverInterface;
|
||||
use Magento\Customer\Api\CustomerRepositoryInterface;
|
||||
|
||||
class AwardFirstAddressPoints implements ObserverInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly BalanceManager $balanceManager,
|
||||
private readonly Config $config,
|
||||
private readonly ResourceConnection $resource,
|
||||
private readonly CustomerRepositoryInterface $customers
|
||||
) {}
|
||||
|
||||
public function execute(Observer $observer): void
|
||||
{
|
||||
$address = $observer->getEvent()->getCustomerAddress();
|
||||
$customerId = (int)($address?->getCustomerId() ?? 0);
|
||||
if (!$this->config->isEnabled() || $customerId <= 0 || !$this->isComplete($address)) { return; }
|
||||
$connection = $this->resource->getConnection();
|
||||
$count = (int)$connection->fetchOne($connection->select()->from($this->resource->getTableName('customer_address_entity'), ['COUNT(*)'])->where('parent_id = ?', $customerId));
|
||||
if ($count > 1) { return; }
|
||||
$websiteId = (int)$this->customers->getById($customerId)->getWebsiteId();
|
||||
$rule = $this->config->earningRule('first_shipping_address');
|
||||
$this->balanceManager->change($customerId, $websiteId, (int)$rule['points'], 'first_shipping_address', 'first_shipping_address:' . $customerId, [
|
||||
'reference_type' => 'customer_address', 'reference_id' => (int)$address->getId(), 'reason' => (string)__($rule['reason'])
|
||||
]);
|
||||
}
|
||||
|
||||
private function isComplete(mixed $address): bool
|
||||
{
|
||||
return $address && trim((string)$address->getCountryId()) !== '' && trim((string)$address->getCity()) !== ''
|
||||
&& trim((string)$address->getPostcode()) !== '' && trim((string)$address->getTelephone()) !== ''
|
||||
&& count(array_filter((array)$address->getStreet(), static fn ($value) => trim((string)$value) !== '')) > 0;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Observer;
|
||||
|
||||
use Esun\Reward\Model\BalanceManager;
|
||||
use Esun\Reward\Model\Config;
|
||||
use Esun\Reward\Model\TierResolver;
|
||||
use Magento\Framework\Event\Observer;
|
||||
use Magento\Framework\Event\ObserverInterface;
|
||||
use Magento\Sales\Model\Order\Invoice;
|
||||
|
||||
class AwardInvoicePoints implements ObserverInterface
|
||||
{
|
||||
public function __construct(private readonly BalanceManager $balanceManager, private readonly Config $config, private readonly TierResolver $tierResolver) {}
|
||||
|
||||
public function execute(Observer $observer): void
|
||||
{
|
||||
/** @var Invoice|null $invoice */ $invoice = $observer->getEvent()->getInvoice();
|
||||
$order = $invoice?->getOrder(); $customerId = (int)($order?->getCustomerId() ?? 0);
|
||||
if (!$invoice || !$order || !$this->config->isEnabled((int)$order->getStoreId()) || $customerId <= 0) { return; }
|
||||
$websiteId = (int)$order->getStore()->getWebsiteId();
|
||||
$account = $this->balanceManager->getAccount($customerId, $websiteId);
|
||||
$tier = $this->tierResolver->resolveEffective((string)$account['tier_code'], (float)$account['lifetime_spend_base'], (int)$order->getStoreId());
|
||||
$rewardShare = (float)$order->getBaseSubtotal() > 0
|
||||
? (float)$order->getData('base_reward_discount_amount') * (float)$invoice->getBaseSubtotal() / (float)$order->getBaseSubtotal()
|
||||
: 0.0;
|
||||
$eligible = max(0.0, (float)$invoice->getBaseSubtotal() + (float)$invoice->getBaseDiscountAmount() - $rewardShare);
|
||||
$rule = $this->config->earningRule('order_earned', (int)$order->getStoreId());
|
||||
$points = (int)floor($eligible * (float)$rule['points'] * (float)$tier['multiplier']);
|
||||
if ($points > 0 && $this->balanceManager->change($customerId, $websiteId, $points, 'order_earned', 'invoice_earned:' . (int)$invoice->getId(), [
|
||||
'reference_type' => 'order', 'reference_id' => (int)$order->getId(), 'reason' => (string)__($rule['reason'], $order->getIncrementId()),
|
||||
'metadata' => ['invoice_id' => (int)$invoice->getId(), 'eligible_amount' => $eligible, 'tier' => $tier['code'], 'multiplier' => $tier['multiplier']]
|
||||
])) {
|
||||
$order->setData('reward_points_earned', (int)$order->getData('reward_points_earned') + $points);
|
||||
$order->setData('reward_tier_code', $tier['code']); $order->setData('reward_multiplier', $tier['multiplier']); $order->save();
|
||||
$this->balanceManager->addLifetimeSpend($customerId, $websiteId, $eligible, (int)$order->getStoreId());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Observer;
|
||||
|
||||
use Esun\Reward\Model\BalanceManager;
|
||||
use Esun\Reward\Model\Config;
|
||||
use Magento\Framework\Event\Observer;
|
||||
use Magento\Framework\Event\ObserverInterface;
|
||||
|
||||
class AwardRegistrationPoints implements ObserverInterface
|
||||
{
|
||||
public function __construct(private readonly BalanceManager $balanceManager, private readonly Config $config) {}
|
||||
|
||||
public function execute(Observer $observer): void
|
||||
{
|
||||
$customer = $observer->getEvent()->getCustomer();
|
||||
$customerId = (int)($customer?->getId() ?? 0);
|
||||
$websiteId = (int)($customer?->getWebsiteId() ?? 0);
|
||||
if (!$this->config->isEnabled() || $customerId <= 0) { return; }
|
||||
$rule = $this->config->earningRule('registration');
|
||||
$this->balanceManager->change($customerId, $websiteId, (int)$rule['points'], 'registration', 'registration:' . $customerId, [
|
||||
'reference_type' => 'customer', 'reference_id' => $customerId, 'reason' => (string)__($rule['reason'])
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Observer;
|
||||
|
||||
use Magento\Framework\Event\Observer;
|
||||
use Magento\Framework\Event\ObserverInterface;
|
||||
|
||||
class CopyRewardToOrder implements ObserverInterface
|
||||
{
|
||||
public function execute(Observer $observer): void
|
||||
{
|
||||
$quote = $observer->getEvent()->getQuote(); $order = $observer->getEvent()->getOrder();
|
||||
foreach (['reward_points_used', 'reward_product_points', 'reward_discount_amount', 'base_reward_discount_amount'] as $field) { $order->setData($field, $quote->getData($field)); }
|
||||
foreach ($quote->getAllItems() as $quoteItem) { if ($quoteItem->getOrderItem()) { $quoteItem->getOrderItem()->setData('reward_redemption', $quoteItem->getData('reward_redemption'))->setData('reward_points_cost', $quoteItem->getData('reward_points_cost')); } }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Observer;
|
||||
|
||||
use Esun\Reward\Model\ReservationManager;
|
||||
use Magento\Framework\Event\Observer;
|
||||
use Magento\Framework\Event\ObserverInterface;
|
||||
|
||||
class RecalculateRedemptionPoints implements ObserverInterface
|
||||
{
|
||||
public function __construct(private readonly ReservationManager $reservations) {}
|
||||
public function execute(Observer $observer): void
|
||||
{
|
||||
$cart=$observer->getEvent()->getCart();$quote=$cart?->getQuote();if(!$quote||!(int)$quote->getCustomerId()){return;}$points=0;
|
||||
foreach($quote->getAllVisibleItems() as $item){if((int)$item->getData('reward_redemption')){$points+=(int)$item->getData('reward_points_cost')*(int)$item->getQty();}}
|
||||
$quote->setData('reward_product_points',$points);$this->reservations->reserve((int)$quote->getCustomerId(),(int)$quote->getStore()->getWebsiteId(),(int)$quote->getId(),$points+(int)$quote->getData('reward_points_used'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Observer;
|
||||
|
||||
use Esun\Reward\Model\BalanceManager;
|
||||
use Magento\Framework\Event\Observer;
|
||||
use Magento\Framework\Event\ObserverInterface;
|
||||
|
||||
class RefundCancelledOrderPoints implements ObserverInterface
|
||||
{
|
||||
public function __construct(private readonly BalanceManager $balances) {}
|
||||
public function execute(Observer $observer): void
|
||||
{
|
||||
$order = $observer->getEvent()->getOrder(); $points = (int)$order->getData('reward_points_used') + (int)$order->getData('reward_product_points');
|
||||
if ($points <= 0 || !(int)$order->getCustomerId()) { return; }
|
||||
$this->balances->change((int)$order->getCustomerId(), (int)$order->getStore()->getWebsiteId(), $points, 'cancel_refund', 'order_cancel_refund:' . (int)$order->getId(), [
|
||||
'reference_type' => 'order', 'reference_id' => (int)$order->getId(), 'reason' => (string)__('Points returned for cancelled order %1', $order->getIncrementId())
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Observer;
|
||||
|
||||
use Esun\Reward\Model\BalanceManager;
|
||||
use Esun\Reward\Model\Config;
|
||||
use Magento\Framework\Event\Observer;
|
||||
use Magento\Framework\Event\ObserverInterface;
|
||||
use Magento\Sales\Model\Order\Creditmemo;
|
||||
|
||||
class ReverseCreditmemoPoints implements ObserverInterface
|
||||
{
|
||||
public function __construct(private readonly BalanceManager $balanceManager, private readonly Config $config) {}
|
||||
public function execute(Observer $observer): void
|
||||
{
|
||||
/** @var Creditmemo|null $creditmemo */ $creditmemo = $observer->getEvent()->getCreditmemo();
|
||||
$order = $creditmemo?->getOrder(); $customerId = (int)($order?->getCustomerId() ?? 0);
|
||||
if (!$creditmemo || !$order || $customerId <= 0 || !$this->config->isEnabled((int)$order->getStoreId())) { return; }
|
||||
$rewardShare = (float)$order->getBaseSubtotal() > 0
|
||||
? (float)$order->getData('base_reward_discount_amount') * (float)$creditmemo->getBaseSubtotal() / (float)$order->getBaseSubtotal()
|
||||
: 0.0;
|
||||
$eligible = max(0.0, (float)$creditmemo->getBaseSubtotal() + (float)$creditmemo->getBaseDiscountAmount() - $rewardShare);
|
||||
$multiplier = max(1.0, (float)$order->getData('reward_multiplier'));
|
||||
$remainingEarned = max(0, (int)$order->getData('reward_points_earned') - (int)$order->getData('reward_points_reversed'));
|
||||
$points = min($remainingEarned, (int)floor($eligible * $this->config->orderRate((int)$order->getStoreId()) * $multiplier));
|
||||
$websiteId = (int)$order->getStore()->getWebsiteId();
|
||||
if ($points > 0) {
|
||||
$this->balanceManager->change($customerId, $websiteId, -$points, 'order_refund_reversal', 'creditmemo_reversal:' . (int)$creditmemo->getId(), [
|
||||
'reference_type' => 'order', 'reference_id' => (int)$order->getId(), 'reason' => (string)__('Points reversed for refund on order %1', $order->getIncrementId()),
|
||||
'metadata' => ['creditmemo_id' => (int)$creditmemo->getId()], 'allow_negative' => true
|
||||
]);
|
||||
$order->setData('reward_points_reversed', (int)$order->getData('reward_points_reversed') + $points);
|
||||
}
|
||||
$returnedProductPoints = 0;
|
||||
foreach ($creditmemo->getAllItems() as $creditmemoItem) {
|
||||
$orderItem = $creditmemoItem->getOrderItem();
|
||||
if ($orderItem && (int)$orderItem->getData('reward_redemption')) {
|
||||
$returnedProductPoints += (int)round((float)$creditmemoItem->getQty() * (int)$orderItem->getData('reward_points_cost'));
|
||||
}
|
||||
}
|
||||
if ($returnedProductPoints > 0) {
|
||||
$this->balanceManager->change($customerId, $websiteId, $returnedProductPoints, 'redemption_refund', 'creditmemo_redemption_refund:' . (int)$creditmemo->getId(), [
|
||||
'reference_type' => 'order', 'reference_id' => (int)$order->getId(), 'reason' => (string)__('Product redemption points returned for order %1', $order->getIncrementId()),
|
||||
'metadata' => ['creditmemo_id' => (int)$creditmemo->getId()]
|
||||
]);
|
||||
}
|
||||
$remainingCashPoints = max(0, (int)$order->getData('reward_points_used') - (int)$order->getData('reward_points_refunded'));
|
||||
$cashPointsToReturn = (float)$order->getBaseSubtotal() > 0
|
||||
? min($remainingCashPoints, (int)round((int)$order->getData('reward_points_used') * (float)$creditmemo->getBaseSubtotal() / (float)$order->getBaseSubtotal()))
|
||||
: 0;
|
||||
if ($cashPointsToReturn > 0) {
|
||||
$this->balanceManager->change($customerId, $websiteId, $cashPointsToReturn, 'checkout_refund', 'creditmemo_checkout_refund:' . (int)$creditmemo->getId(), [
|
||||
'reference_type' => 'order', 'reference_id' => (int)$order->getId(), 'reason' => (string)__('Checkout points returned for order %1', $order->getIncrementId()),
|
||||
'metadata' => ['creditmemo_id' => (int)$creditmemo->getId()]
|
||||
]);
|
||||
$order->setData('reward_points_refunded', (int)$order->getData('reward_points_refunded') + $cashPointsToReturn);
|
||||
}
|
||||
$order->save();
|
||||
$this->balanceManager->addLifetimeSpend($customerId, $websiteId, -$eligible, (int)$order->getStoreId());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Observer;
|
||||
|
||||
use Esun\Reward\Model\BalanceManager;
|
||||
use Esun\Reward\Model\ReservationManager;
|
||||
use Magento\Framework\Event\Observer;
|
||||
use Magento\Framework\Event\ObserverInterface;
|
||||
|
||||
class SpendOrderPoints implements ObserverInterface
|
||||
{
|
||||
public function __construct(private readonly BalanceManager $balances, private readonly ReservationManager $reservations) {}
|
||||
public function execute(Observer $observer): void
|
||||
{
|
||||
$order = $observer->getEvent()->getOrder(); $quote = $observer->getEvent()->getQuote(); $points = (int)$order->getData('reward_points_used') + (int)$order->getData('reward_product_points');
|
||||
if ($points <= 0 || !(int)$order->getCustomerId()) { return; }
|
||||
$this->balances->change((int)$order->getCustomerId(), (int)$order->getStore()->getWebsiteId(), -$points, 'checkout_spend', 'order_spend:' . (int)$order->getId(), [
|
||||
'reference_type' => 'order', 'reference_id' => (int)$order->getId(), 'reason' => (string)__('Points used on order %1', $order->getIncrementId())
|
||||
]);
|
||||
$this->reservations->markUsed((int)$quote->getId());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Plugin\Checkout;
|
||||
|
||||
use Amasty\CheckoutCore\Block\Onepage\LayoutProcessor;
|
||||
|
||||
/**
|
||||
* Places checkout promotions inside Order Summary, directly before totals.
|
||||
*/
|
||||
class SummaryLayoutProcessorPlugin
|
||||
{
|
||||
public function afterProcess(LayoutProcessor $subject, array $jsLayout): array
|
||||
{
|
||||
$checkout = &$jsLayout['components']['checkout']['children'];
|
||||
$sidebar = &$checkout['sidebar']['children'];
|
||||
$summary = &$sidebar['summary']['children'];
|
||||
|
||||
if (!is_array($summary)) {
|
||||
return $jsLayout;
|
||||
}
|
||||
|
||||
$summary['cart_items']['sortOrder'] = 10;
|
||||
|
||||
// Amasty moves Magento's coupon component to summary_additional, which
|
||||
// renders after totals. Move that same component above totals instead.
|
||||
$additional = &$sidebar['summary_additional']['children'];
|
||||
if (isset($additional['discount']) && is_array($additional['discount'])) {
|
||||
$discount = $additional['discount'];
|
||||
unset($additional['discount']);
|
||||
$discount['sortOrder'] = 20;
|
||||
$discount['config']['template'] = 'Magento_SalesRule/payment/discount';
|
||||
$summary['discount-code'] = $discount;
|
||||
}
|
||||
|
||||
// Depending on Amasty configuration, third-party payment additions can
|
||||
// be moved or renamed before this processor finishes. Extract the
|
||||
// component wherever it ended up; create it when Amasty removed it.
|
||||
$reward = $this->extractComponent(
|
||||
$checkout,
|
||||
'Esun_Reward/js/view/payment/reward'
|
||||
) ?? [
|
||||
'component' => 'Esun_Reward/js/view/payment/reward'
|
||||
];
|
||||
$reward['sortOrder'] = 21;
|
||||
$summary['esun-reward'] = $reward;
|
||||
|
||||
// Amasty supplies an expandable details template. Use the theme's
|
||||
// always-open Magento template so product options display immediately.
|
||||
if (isset($summary['cart_items']['children']['details'])) {
|
||||
$summary['cart_items']['children']['details']['config']['template'] =
|
||||
'Magento_Checkout/summary/item/details';
|
||||
}
|
||||
|
||||
$summary['totals']['sortOrder'] = 30;
|
||||
|
||||
return $jsLayout;
|
||||
}
|
||||
|
||||
private function extractComponent(array &$node, string $component): ?array
|
||||
{
|
||||
foreach (array_keys($node) as $key) {
|
||||
if (!isset($node[$key]) || !is_array($node[$key])) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (($node[$key]['component'] ?? null) === $component) {
|
||||
$result = $node[$key];
|
||||
unset($node[$key]);
|
||||
return $result;
|
||||
}
|
||||
|
||||
$result = $this->extractComponent($node[$key], $component);
|
||||
if ($result !== null) {
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Plugin\CustomerData;
|
||||
|
||||
use Esun\Reward\Model\BalanceManager;
|
||||
use Esun\Reward\Model\Config;
|
||||
use Magento\Checkout\CustomerData\Cart;
|
||||
use Magento\Checkout\Helper\Data as CheckoutHelper;
|
||||
use Magento\Checkout\Model\Cart as CheckoutCart;
|
||||
use Magento\Customer\Helper\Session\CurrentCustomer;
|
||||
|
||||
class CartPlugin
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CheckoutCart $checkoutCart,
|
||||
private readonly CurrentCustomer $currentCustomer,
|
||||
private readonly BalanceManager $balances,
|
||||
private readonly Config $config,
|
||||
private readonly CheckoutHelper $checkoutHelper
|
||||
) {}
|
||||
public function afterGetSectionData(Cart $subject, array $result): array
|
||||
{
|
||||
// Use the same cart model and current-customer helper as Magento's cart
|
||||
// and customer sections. Injecting fresh session models here can create
|
||||
// a second, empty quote/session during customer/section/load.
|
||||
$quote = $this->checkoutCart->getQuote();
|
||||
$customerId = (int)$this->currentCustomer->getCustomerId()
|
||||
?: (int)$quote->getCustomerId();
|
||||
$balance = $customerId > 0 ? (int)$this->balances->getAccount($customerId, (int)$quote->getStore()->getWebsiteId())['balance'] : 0;
|
||||
$result['reward'] = ['logged_in' => $customerId > 0, 'balance' => $balance, 'applied_points' => (int)$quote->getData('reward_points_used'), 'maximum' => $this->config->maxCheckoutPoints((int)$quote->getStoreId()), 'rate' => $this->config->redemptionRate((int)$quote->getStoreId())];
|
||||
if (isset($result['drawer_totals'])) { $result['drawer_totals']['reward_discount'] = (float)$quote->getData('reward_discount_amount') > 0 ? '-' . $this->checkoutHelper->formatPrice((float)$quote->getData('reward_discount_amount')) : ''; }
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
# 后台导入旧站积分和会员等级
|
||||
|
||||
后台路径:`System → Data Transfer → Import`。
|
||||
|
||||
选择实体:`Customer Reward Points and Tier`。
|
||||
|
||||
CSV 使用 UTF-8 编码,只包含三列:
|
||||
|
||||
```csv
|
||||
email,member_tier,points
|
||||
customer@example.com,VIP III,1200
|
||||
```
|
||||
|
||||
规则:
|
||||
|
||||
- 通过邮箱匹配已经导入 Magento 的客户。
|
||||
- 一个邮箱只匹配一个 Website 时,自动采用该 Website。
|
||||
- 同一邮箱出现在多个 Website 时,`Check Data` 报错,必须人工确认。
|
||||
- `VIP I` 或 `Bronze Maker` → `bronze`。
|
||||
- `VIP II` 或 `Silver Maker` → `silver`。
|
||||
- `VIP III` 或 `Gold Maker` → `gold`。
|
||||
- 积分是导入后的目标可用余额,只接受非负整数,不进行四舍五入。
|
||||
- 正式导入会写入 `migration` 类型积分流水。
|
||||
|
||||
先点击 `Check Data`,全部通过后再点击 `Import`。
|
||||
|
||||
后台的 `Download Sample File` 会下载模块内的 `Files/Sample/esun_reward.csv`。
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Setup\Patch\Data;
|
||||
|
||||
use Magento\Catalog\Model\Product;
|
||||
use Magento\Eav\Setup\EavSetupFactory;
|
||||
use Magento\Framework\Setup\ModuleDataSetupInterface;
|
||||
use Magento\Framework\Setup\Patch\DataPatchInterface;
|
||||
|
||||
class AddRewardProductAttributes implements DataPatchInterface
|
||||
{
|
||||
public function __construct(private readonly ModuleDataSetupInterface $setup, private readonly EavSetupFactory $eavSetupFactory) {}
|
||||
public function apply(): self
|
||||
{
|
||||
$this->setup->getConnection()->startSetup(); $eav = $this->eavSetupFactory->create(['setup' => $this->setup]);
|
||||
$eav->addAttribute(Product::ENTITY, 'reward_redeemable', ['type'=>'int','label'=>'Available for Points Redemption','input'=>'boolean','source'=>\Magento\Eav\Model\Entity\Attribute\Source\Boolean::class,'default'=>0,'required'=>false,'global'=>\Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_WEBSITE,'group'=>'General','visible'=>true,'user_defined'=>true]);
|
||||
$eav->addAttribute(Product::ENTITY, 'reward_points_cost', ['type'=>'int','label'=>'Redemption Points Cost','input'=>'text','default'=>0,'required'=>false,'global'=>\Magento\Eav\Model\Entity\Attribute\ScopedAttributeInterface::SCOPE_WEBSITE,'group'=>'General','visible'=>true,'user_defined'=>true,'validate_rules'=>'{"input_validation":"validate-digits"}']);
|
||||
$this->setup->getConnection()->endSetup(); return $this;
|
||||
}
|
||||
public static function getDependencies(): array { return []; }
|
||||
public function getAliases(): array { return []; }
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\Reward\Setup\Patch\Data;
|
||||
|
||||
use Magento\Framework\App\ResourceConnection;
|
||||
use Magento\Framework\Setup\ModuleDataSetupInterface;
|
||||
use Magento\Framework\Setup\Patch\DataPatchInterface;
|
||||
|
||||
class ConsolidateGlobalRewardBalances implements DataPatchInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly ModuleDataSetupInterface $moduleDataSetup,
|
||||
private readonly ResourceConnection $resource
|
||||
) {}
|
||||
|
||||
public function apply(): self
|
||||
{
|
||||
$connection = $this->moduleDataSetup->getConnection();
|
||||
$accountTable = $this->resource->getTableName('esun_reward_account');
|
||||
$transactionTable = $this->resource->getTableName('esun_reward_transaction');
|
||||
$this->moduleDataSetup->startSetup();
|
||||
try {
|
||||
$customerIds = $connection->fetchCol(
|
||||
$connection->select()->from($accountTable, ['customer_id'])->group('customer_id')->having('COUNT(*) > 1')
|
||||
);
|
||||
foreach ($customerIds as $customerId) {
|
||||
$rows = $connection->fetchAll(
|
||||
$connection->select()->from($accountTable)->where('customer_id = ?', (int)$customerId)->order('account_id ASC')
|
||||
);
|
||||
$primaryId = (int)$rows[0]['account_id'];
|
||||
$connection->update($accountTable, [
|
||||
'balance' => (int)array_sum(array_column($rows, 'balance')),
|
||||
'pending_balance' => (int)array_sum(array_column($rows, 'pending_balance')),
|
||||
'lifetime_earned' => (int)array_sum(array_column($rows, 'lifetime_earned')),
|
||||
'lifetime_spend_base' => (float)array_sum(array_column($rows, 'lifetime_spend_base')),
|
||||
], ['account_id = ?' => $primaryId]);
|
||||
$connection->update($accountTable, [
|
||||
'balance' => 0, 'pending_balance' => 0, 'lifetime_earned' => 0, 'lifetime_spend_base' => 0,
|
||||
], ['customer_id = ?' => (int)$customerId, 'account_id <> ?' => $primaryId]);
|
||||
}
|
||||
|
||||
$connection->update(
|
||||
$transactionTable,
|
||||
['reason' => 'Approved product review reward'],
|
||||
['type IN (?)' => ['review_media', 'review_text']]
|
||||
);
|
||||
foreach ($connection->fetchCol($connection->select()->from($transactionTable, ['customer_id'])->distinct()) as $customerId) {
|
||||
$balance = 0;
|
||||
$transactions = $connection->fetchAll(
|
||||
$connection->select()->from($transactionTable, ['transaction_id', 'points_delta'])
|
||||
->where('customer_id = ?', (int)$customerId)->order('transaction_id ASC')
|
||||
);
|
||||
foreach ($transactions as $transaction) {
|
||||
$balance += (int)$transaction['points_delta'];
|
||||
$connection->update($transactionTable, ['balance_after' => $balance], [
|
||||
'transaction_id = ?' => (int)$transaction['transaction_id'],
|
||||
]);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
$this->moduleDataSetup->endSetup();
|
||||
}
|
||||
return $this;
|
||||
}
|
||||
|
||||
public static function getDependencies(): array { return []; }
|
||||
public function getAliases(): array { return []; }
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:Acl/etc/acl.xsd">
|
||||
<acl>
|
||||
<resources>
|
||||
<resource id="Magento_Backend::admin">
|
||||
<resource id="Magento_Customer::customer" title="Customers" translate="title">
|
||||
<resource id="Esun_Reward::view" title="View Reward Points" translate="title" sortOrder="80"/>
|
||||
<resource id="Esun_Reward::adjust" title="Adjust Reward Points" translate="title" sortOrder="90"/>
|
||||
</resource>
|
||||
<resource id="Magento_Backend::stores">
|
||||
<resource id="Magento_Backend::stores_settings">
|
||||
<resource id="Magento_Config::config">
|
||||
<resource id="Esun_Reward::configuration" title="Reward Points Configuration" translate="title" sortOrder="90"/>
|
||||
</resource>
|
||||
</resource>
|
||||
</resource>
|
||||
</resource>
|
||||
</resources>
|
||||
</acl>
|
||||
</config>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
|
||||
<router id="admin"><route id="esun_reward" frontName="esun_reward"><module name="Esun_Reward" before="Magento_Backend"/></route></router>
|
||||
</config>
|
||||
@@ -0,0 +1,49 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Config:etc/system_file.xsd">
|
||||
<system>
|
||||
<section id="esun_reward" translate="label" type="text" sortOrder="350"
|
||||
showInDefault="1" showInWebsite="1" showInStore="1">
|
||||
<label>Reward Points</label>
|
||||
<tab>esun</tab>
|
||||
<resource>Esun_Reward::configuration</resource>
|
||||
<group id="general" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
|
||||
<label>General</label>
|
||||
<field id="enabled" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
|
||||
<label>Enabled</label>
|
||||
<source_model>Magento\Config\Model\Config\Source\Yesno</source_model>
|
||||
</field>
|
||||
</group>
|
||||
<group id="earning" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1">
|
||||
<label>Earning Rules</label>
|
||||
<field id="items" translate="label comment" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
|
||||
<label>Earning Rule Items</label>
|
||||
<frontend_model>Esun\Reward\Block\Adminhtml\System\Config\Form\Field\EarningRuleItems</frontend_model>
|
||||
<backend_model>Esun\Reward\Model\Config\Backend\EarningRuleItems</backend_model>
|
||||
<comment>Select a supported trigger event and configure its reward value, customer-facing activity name and history reason. Adding a row does not create a new event type. For Paid Order, Reward Points means points per currency unit and %1 in Reason is replaced by the order number.</comment>
|
||||
</field>
|
||||
</group>
|
||||
<group id="spending" translate="label" type="text" sortOrder="30" showInDefault="1" showInWebsite="1" showInStore="1">
|
||||
<label>Spending Rules</label>
|
||||
<field id="points_per_dollar" translate="label" type="text" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1"><label>Points Required per Currency Unit</label><validate>validate-number validate-greater-than-zero</validate></field>
|
||||
<field id="max_checkout_points" translate="label" type="text" sortOrder="20" showInDefault="1" showInWebsite="1" showInStore="1"><label>Maximum Checkout Points</label><validate>validate-number validate-zero-or-greater</validate></field>
|
||||
</group>
|
||||
<group id="tiers" translate="label" type="text" sortOrder="40" showInDefault="1" showInWebsite="1" showInStore="1">
|
||||
<label>VIP Tiers</label>
|
||||
<field id="items" translate="label comment" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
|
||||
<label>Tier Items</label>
|
||||
<frontend_model>Esun\Reward\Block\Adminhtml\System\Config\Form\Field\TierItems</frontend_model>
|
||||
<backend_model>Esun\Reward\Model\Config\Backend\TierItems</backend_model>
|
||||
<comment>Set the lifetime spend threshold and points multiplier for each tier. Tiers are evaluated from the highest threshold down.</comment>
|
||||
</field>
|
||||
</group>
|
||||
<group id="review" translate="label" type="text" sortOrder="50" showInDefault="1" showInWebsite="1" showInStore="1">
|
||||
<label>Review Eligibility</label>
|
||||
<field id="eligibility" translate="label" type="select" sortOrder="10" showInDefault="1" showInWebsite="1" showInStore="1">
|
||||
<label>Customers Can Review After</label>
|
||||
<source_model>Esun\Reward\Model\Config\Source\ReviewEligibility</source_model>
|
||||
</field>
|
||||
</group>
|
||||
</section>
|
||||
</system>
|
||||
</config>
|
||||
@@ -0,0 +1,18 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Store:etc/config.xsd">
|
||||
<default><esun_reward>
|
||||
<general><enabled>1</enabled></general>
|
||||
<earning>
|
||||
<registration_points>100</registration_points><first_address_points>100</first_address_points>
|
||||
<points_per_dollar>1</points_per_dollar><review_text_points>20</review_text_points>
|
||||
<review_media_points>40</review_media_points><social_share_points>300</social_share_points>
|
||||
</earning>
|
||||
<spending><points_per_dollar>100</points_per_dollar><max_checkout_points>1500</max_checkout_points></spending>
|
||||
<tiers>
|
||||
<silver_threshold>3000</silver_threshold><silver_multiplier>1.2</silver_multiplier>
|
||||
<gold_threshold>7000</gold_threshold><gold_multiplier>1.5</gold_multiplier>
|
||||
</tiers>
|
||||
<review><eligibility>payment_success</eligibility></review>
|
||||
</esun_reward></default>
|
||||
</config>
|
||||
@@ -0,0 +1,89 @@
|
||||
<?xml version="1.0"?>
|
||||
<schema xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:Setup/Declaration/Schema/etc/schema.xsd">
|
||||
<table name="esun_reward_account" resource="default" engine="innodb" comment="eSUN Reward Accounts">
|
||||
<column xsi:type="int" name="account_id" unsigned="true" nullable="false" identity="true" comment="Account ID"/>
|
||||
<column xsi:type="int" name="customer_id" unsigned="true" nullable="false" comment="Customer ID"/>
|
||||
<column xsi:type="smallint" name="website_id" unsigned="true" nullable="false" comment="Website ID"/>
|
||||
<column xsi:type="int" name="balance" nullable="false" default="0" comment="Available Points"/>
|
||||
<column xsi:type="int" name="pending_balance" nullable="false" default="0" comment="Pending Points"/>
|
||||
<column xsi:type="int" name="lifetime_earned" unsigned="true" nullable="false" default="0" comment="Lifetime Earned Points"/>
|
||||
<column xsi:type="decimal" name="lifetime_spend_base" scale="4" precision="20" nullable="false" default="0" comment="Lifetime Base Spend"/>
|
||||
<column xsi:type="varchar" name="tier_code" nullable="false" length="32" default="bronze" comment="Tier Code"/>
|
||||
<column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" comment="Created At"/>
|
||||
<column xsi:type="timestamp" name="updated_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="true" comment="Updated At"/>
|
||||
<constraint xsi:type="primary" referenceId="PRIMARY"><column name="account_id"/></constraint>
|
||||
<constraint xsi:type="unique" referenceId="ESUN_REWARD_ACCOUNT_CUSTOMER_WEBSITE_UNQ">
|
||||
<column name="customer_id"/><column name="website_id"/>
|
||||
</constraint>
|
||||
<constraint xsi:type="foreign" referenceId="ESUN_REWARD_ACCOUNT_CUSTOMER_ID_CUSTOMER_ENTITY_ENTITY_ID"
|
||||
table="esun_reward_account" column="customer_id" referenceTable="customer_entity"
|
||||
referenceColumn="entity_id" onDelete="CASCADE"/>
|
||||
</table>
|
||||
|
||||
<table name="esun_reward_transaction" resource="default" engine="innodb" comment="eSUN Reward Transactions">
|
||||
<column xsi:type="bigint" name="transaction_id" unsigned="true" nullable="false" identity="true" comment="Transaction ID"/>
|
||||
<column xsi:type="int" name="customer_id" unsigned="true" nullable="false" comment="Customer ID"/>
|
||||
<column xsi:type="smallint" name="website_id" unsigned="true" nullable="false" comment="Website ID"/>
|
||||
<column xsi:type="int" name="points_delta" nullable="false" comment="Points Delta"/>
|
||||
<column xsi:type="int" name="balance_after" nullable="false" comment="Balance After"/>
|
||||
<column xsi:type="varchar" name="type" nullable="false" length="64" comment="Transaction Type"/>
|
||||
<column xsi:type="varchar" name="status" nullable="false" length="24" default="available" comment="Status"/>
|
||||
<column xsi:type="varchar" name="reference_type" nullable="true" length="32" comment="Reference Type"/>
|
||||
<column xsi:type="varchar" name="reference_id" nullable="true" length="64" comment="Reference ID"/>
|
||||
<column xsi:type="varchar" name="unique_key" nullable="false" length="191" comment="Idempotency Key"/>
|
||||
<column xsi:type="text" name="reason" nullable="true" comment="Reason"/>
|
||||
<column xsi:type="int" name="admin_user_id" unsigned="true" nullable="true" comment="Admin User ID"/>
|
||||
<column xsi:type="text" name="metadata" nullable="true" comment="JSON Metadata"/>
|
||||
<column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" comment="Created At"/>
|
||||
<constraint xsi:type="primary" referenceId="PRIMARY"><column name="transaction_id"/></constraint>
|
||||
<constraint xsi:type="unique" referenceId="ESUN_REWARD_TRANSACTION_UNIQUE_KEY_UNQ"><column name="unique_key"/></constraint>
|
||||
<constraint xsi:type="foreign" referenceId="ESUN_REWARD_TRANSACTION_CUSTOMER_ID_CUSTOMER_ENTITY_ENTITY_ID"
|
||||
table="esun_reward_transaction" column="customer_id" referenceTable="customer_entity"
|
||||
referenceColumn="entity_id" onDelete="CASCADE"/>
|
||||
<index referenceId="ESUN_REWARD_TRANSACTION_CUSTOMER_CREATED" indexType="btree">
|
||||
<column name="customer_id"/><column name="created_at"/>
|
||||
</index>
|
||||
</table>
|
||||
|
||||
<table name="esun_reward_reservation" resource="checkout" engine="innodb" comment="eSUN Reward Quote Reservations">
|
||||
<column xsi:type="int" name="reservation_id" unsigned="true" nullable="false" identity="true" comment="Reservation ID"/>
|
||||
<column xsi:type="int" name="customer_id" unsigned="true" nullable="false" comment="Customer ID"/>
|
||||
<column xsi:type="int" name="quote_id" unsigned="true" nullable="false" comment="Quote ID"/>
|
||||
<column xsi:type="int" name="points" unsigned="true" nullable="false" comment="Reserved Points"/>
|
||||
<column xsi:type="varchar" name="status" nullable="false" length="24" default="active" comment="Status"/>
|
||||
<column xsi:type="timestamp" name="expires_at" nullable="true" comment="Expires At"/>
|
||||
<column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP" comment="Created At"/>
|
||||
<column xsi:type="timestamp" name="updated_at" nullable="false" default="CURRENT_TIMESTAMP" on_update="true" comment="Updated At"/>
|
||||
<constraint xsi:type="primary" referenceId="PRIMARY"><column name="reservation_id"/></constraint>
|
||||
<constraint xsi:type="unique" referenceId="ESUN_REWARD_RESERVATION_QUOTE_UNQ"><column name="quote_id"/></constraint>
|
||||
<constraint xsi:type="foreign" referenceId="ESUN_REWARD_RESERVATION_QUOTE_ID_QUOTE_ENTITY_ID"
|
||||
table="esun_reward_reservation" column="quote_id" referenceTable="quote" referenceColumn="entity_id" onDelete="CASCADE"/>
|
||||
</table>
|
||||
|
||||
<table name="quote" resource="checkout" engine="innodb" comment="Sales Flat Quote">
|
||||
<column xsi:type="int" name="reward_points_used" unsigned="true" nullable="false" default="0" comment="Reward Points Used"/>
|
||||
<column xsi:type="decimal" name="reward_discount_amount" scale="4" precision="20" nullable="false" default="0" comment="Reward Discount"/>
|
||||
<column xsi:type="decimal" name="base_reward_discount_amount" scale="4" precision="20" nullable="false" default="0" comment="Base Reward Discount"/>
|
||||
<column xsi:type="int" name="reward_product_points" unsigned="true" nullable="false" default="0" comment="Reward Product Points"/>
|
||||
</table>
|
||||
<table name="quote_item" resource="checkout" engine="innodb" comment="Sales Flat Quote Item">
|
||||
<column xsi:type="smallint" name="reward_redemption" unsigned="true" nullable="false" default="0" comment="Reward Redemption Item"/>
|
||||
<column xsi:type="int" name="reward_points_cost" unsigned="true" nullable="false" default="0" comment="Reward Points Cost"/>
|
||||
</table>
|
||||
<table name="sales_order" resource="sales" engine="innodb" comment="Sales Flat Order">
|
||||
<column xsi:type="int" name="reward_points_used" unsigned="true" nullable="false" default="0" comment="Reward Points Used"/>
|
||||
<column xsi:type="int" name="reward_points_earned" unsigned="true" nullable="false" default="0" comment="Reward Points Earned"/>
|
||||
<column xsi:type="decimal" name="reward_discount_amount" scale="4" precision="20" nullable="false" default="0" comment="Reward Discount"/>
|
||||
<column xsi:type="decimal" name="base_reward_discount_amount" scale="4" precision="20" nullable="false" default="0" comment="Base Reward Discount"/>
|
||||
<column xsi:type="varchar" name="reward_tier_code" nullable="true" length="32" comment="Reward Tier Snapshot"/>
|
||||
<column xsi:type="decimal" name="reward_multiplier" scale="4" precision="12" nullable="false" default="1" comment="Reward Multiplier Snapshot"/>
|
||||
<column xsi:type="int" name="reward_product_points" unsigned="true" nullable="false" default="0" comment="Reward Product Points"/>
|
||||
<column xsi:type="int" name="reward_points_refunded" unsigned="true" nullable="false" default="0" comment="Reward Points Refunded"/>
|
||||
<column xsi:type="int" name="reward_points_reversed" unsigned="true" nullable="false" default="0" comment="Earned Points Reversed"/>
|
||||
</table>
|
||||
<table name="sales_order_item" resource="sales" engine="innodb" comment="Sales Flat Order Item">
|
||||
<column xsi:type="smallint" name="reward_redemption" unsigned="true" nullable="false" default="0" comment="Reward Redemption Item"/>
|
||||
<column xsi:type="int" name="reward_points_cost" unsigned="true" nullable="false" default="0" comment="Reward Points Cost"/>
|
||||
</table>
|
||||
</schema>
|
||||
@@ -0,0 +1,97 @@
|
||||
{
|
||||
"esun_reward_account": {
|
||||
"column": {
|
||||
"account_id": true,
|
||||
"customer_id": true,
|
||||
"website_id": true,
|
||||
"balance": true,
|
||||
"pending_balance": true,
|
||||
"lifetime_earned": true,
|
||||
"lifetime_spend_base": true,
|
||||
"tier_code": true,
|
||||
"created_at": true,
|
||||
"updated_at": true
|
||||
},
|
||||
"constraint": {
|
||||
"PRIMARY": true,
|
||||
"ESUN_REWARD_ACCOUNT_CUSTOMER_ID_WEBSITE_ID": true,
|
||||
"ESUN_REWARD_ACCOUNT_CUSTOMER_ID_CUSTOMER_ENTITY_ENTITY_ID": true
|
||||
}
|
||||
},
|
||||
"esun_reward_transaction": {
|
||||
"column": {
|
||||
"transaction_id": true,
|
||||
"customer_id": true,
|
||||
"website_id": true,
|
||||
"points_delta": true,
|
||||
"balance_after": true,
|
||||
"type": true,
|
||||
"status": true,
|
||||
"reference_type": true,
|
||||
"reference_id": true,
|
||||
"unique_key": true,
|
||||
"reason": true,
|
||||
"admin_user_id": true,
|
||||
"metadata": true,
|
||||
"created_at": true
|
||||
},
|
||||
"index": {
|
||||
"ESUN_REWARD_TRANSACTION_CUSTOMER_ID_CREATED_AT": true
|
||||
},
|
||||
"constraint": {
|
||||
"PRIMARY": true,
|
||||
"ESUN_REWARD_TRANSACTION_UNIQUE_KEY": true,
|
||||
"ESUN_REWARD_TRANSACTION_CUSTOMER_ID_CUSTOMER_ENTITY_ENTITY_ID": true
|
||||
}
|
||||
},
|
||||
"esun_reward_reservation": {
|
||||
"column": {
|
||||
"reservation_id": true,
|
||||
"customer_id": true,
|
||||
"quote_id": true,
|
||||
"points": true,
|
||||
"status": true,
|
||||
"expires_at": true,
|
||||
"created_at": true,
|
||||
"updated_at": true
|
||||
},
|
||||
"constraint": {
|
||||
"PRIMARY": true,
|
||||
"ESUN_REWARD_RESERVATION_QUOTE_ID": true,
|
||||
"ESUN_REWARD_RESERVATION_QUOTE_ID_QUOTE_ENTITY_ID": true
|
||||
}
|
||||
},
|
||||
"quote": {
|
||||
"column": {
|
||||
"reward_points_used": true,
|
||||
"reward_discount_amount": true,
|
||||
"base_reward_discount_amount": true,
|
||||
"reward_product_points": true
|
||||
}
|
||||
},
|
||||
"quote_item": {
|
||||
"column": {
|
||||
"reward_redemption": true,
|
||||
"reward_points_cost": true
|
||||
}
|
||||
},
|
||||
"sales_order": {
|
||||
"column": {
|
||||
"reward_points_used": true,
|
||||
"reward_points_earned": true,
|
||||
"reward_discount_amount": true,
|
||||
"base_reward_discount_amount": true,
|
||||
"reward_tier_code": true,
|
||||
"reward_multiplier": true,
|
||||
"reward_product_points": true,
|
||||
"reward_points_refunded": true,
|
||||
"reward_points_reversed": true
|
||||
}
|
||||
},
|
||||
"sales_order_item": {
|
||||
"column": {
|
||||
"reward_redemption": true,
|
||||
"reward_points_cost": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
|
||||
<type name="Magento\ImportExport\Model\Import\SampleFileProvider">
|
||||
<arguments>
|
||||
<argument name="samples" xsi:type="array">
|
||||
<item name="esun_reward" xsi:type="string">Esun_Reward</item>
|
||||
</argument>
|
||||
</arguments>
|
||||
</type>
|
||||
</config>
|
||||
@@ -0,0 +1,29 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
|
||||
<event name="customer_register_success">
|
||||
<observer name="esun_reward_registration" instance="Esun\Reward\Observer\AwardRegistrationPoints"/>
|
||||
</event>
|
||||
<event name="customer_address_save_after">
|
||||
<observer name="esun_reward_first_address" instance="Esun\Reward\Observer\AwardFirstAddressPoints"/>
|
||||
</event>
|
||||
<event name="sales_order_invoice_pay">
|
||||
<observer name="esun_reward_invoice_pay" instance="Esun\Reward\Observer\AwardInvoicePoints"/>
|
||||
</event>
|
||||
<event name="sales_order_creditmemo_refund">
|
||||
<observer name="esun_reward_creditmemo_refund" instance="Esun\Reward\Observer\ReverseCreditmemoPoints"/>
|
||||
</event>
|
||||
<event name="review_save_after">
|
||||
<observer name="esun_reward_review_approved" instance="Esun\Reward\Observer\AwardApprovedReviewPoints"/>
|
||||
</event>
|
||||
<event name="sales_model_service_quote_submit_before">
|
||||
<observer name="esun_reward_copy_to_order" instance="Esun\Reward\Observer\CopyRewardToOrder"/>
|
||||
</event>
|
||||
<event name="sales_model_service_quote_submit_success">
|
||||
<observer name="esun_reward_spend_order_points" instance="Esun\Reward\Observer\SpendOrderPoints"/>
|
||||
</event>
|
||||
<event name="order_cancel_after">
|
||||
<observer name="esun_reward_refund_cancelled_points" instance="Esun\Reward\Observer\RefundCancelledOrderPoints"/>
|
||||
</event>
|
||||
<event name="checkout_cart_save_after"><observer name="esun_reward_recalculate_redemptions" instance="Esun\Reward\Observer\RecalculateRedemptionPoints"/></event>
|
||||
</config>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:DataObject/etc/fieldset.xsd">
|
||||
<scope id="global"><fieldset id="quote_convert_item">
|
||||
<field name="reward_redemption"><aspect name="to_order_item"/></field>
|
||||
<field name="reward_points_cost"><aspect name="to_order_item"/></field>
|
||||
</fieldset></scope>
|
||||
</config>
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
|
||||
<type name="Magento\Checkout\Model\CompositeConfigProvider">
|
||||
<arguments>
|
||||
<argument name="configProviders" xsi:type="array">
|
||||
<item name="esun_reward" xsi:type="object">Esun\Reward\Model\CheckoutConfigProvider</item>
|
||||
</argument>
|
||||
</arguments>
|
||||
</type>
|
||||
<type name="Magento\Checkout\CustomerData\Cart"><plugin name="esun_reward_cart_customer_data" type="Esun\Reward\Plugin\CustomerData\CartPlugin" sortOrder="200"/></type>
|
||||
<type name="Amasty\CheckoutCore\Block\Onepage\LayoutProcessor">
|
||||
<plugin name="esun_reward_checkout_summary_layout"
|
||||
type="Esun\Reward\Plugin\Checkout\SummaryLayoutProcessorPlugin"
|
||||
sortOrder="200"/>
|
||||
</type>
|
||||
</config>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
|
||||
<router id="standard"><route id="esun_reward" frontName="reward"><module name="Esun_Reward"/></route></router>
|
||||
</config>
|
||||
@@ -0,0 +1,7 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_ImportExport:etc/import.xsd">
|
||||
<entity name="esun_reward" label="Customer Reward Points and Tier"
|
||||
model="Esun\Reward\Model\Import\Reward"
|
||||
behaviorModel="Magento\ImportExport\Model\Source\Import\Behavior\Basic"/>
|
||||
</config>
|
||||
@@ -0,0 +1,17 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
|
||||
<module name="Esun_Reward">
|
||||
<sequence>
|
||||
<module name="Magento_Customer"/>
|
||||
<module name="Magento_ImportExport"/>
|
||||
<module name="Magento_Sales"/>
|
||||
<module name="Magento_Quote"/>
|
||||
<module name="Magento_Checkout"/>
|
||||
<module name="Magento_Review"/>
|
||||
<module name="Amasty_CheckoutCore"/>
|
||||
<module name="Esun_Cart"/>
|
||||
<module name="Esun_Review"/>
|
||||
</sequence>
|
||||
</module>
|
||||
</config>
|
||||
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Sales:etc/sales.xsd">
|
||||
<section name="quote"><group name="totals"><item name="reward_discount" instance="Esun\Reward\Model\Total\Quote\RewardDiscount" sort_order="500"/></group></section>
|
||||
</config>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
use Magento\Framework\Component\ComponentRegistrar;
|
||||
|
||||
ComponentRegistrar::register(ComponentRegistrar::MODULE, 'Esun_Reward', __DIR__);
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0"?>
|
||||
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
|
||||
<body><referenceContainer name="content">
|
||||
<block class="Esun\Reward\Block\Adminhtml\Customer\Reward" name="esun.customer.reward" template="Esun_Reward::customer/reward.phtml" after="customer_form"/>
|
||||
</referenceContainer></body>
|
||||
</page>
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
/** @var \Esun\Reward\Block\Adminhtml\Customer\Reward $block */
|
||||
/** @var \Magento\Framework\Escaper $escaper */
|
||||
$data = $block->getRewardData();
|
||||
if (!$data) { return; }
|
||||
?>
|
||||
<section class="admin__page-section">
|
||||
<div class="admin__page-section-title"><span class="title"><?= $escaper->escapeHtml(__('Reward Points')) ?></span></div>
|
||||
<div class="admin__page-section-content">
|
||||
<div class="admin__page-section-item"><strong><?= $escaper->escapeHtml(__('Available Balance')) ?>:</strong> <?= (int)$data['balance'] ?> <strong><?= $escaper->escapeHtml(__('VIP Tier')) ?>:</strong> <?= $escaper->escapeHtml($data['tier']['label']) ?> (<?= $escaper->escapeHtml((string)$data['tier']['multiplier']) ?>×) <strong><?= $escaper->escapeHtml(__('Lifetime Spend')) ?>:</strong> $<?= $escaper->escapeHtml(number_format((float)$data['lifetime_spend_base'], 2)) ?></div>
|
||||
<form method="post" action="<?= $escaper->escapeUrl($block->getAdjustUrl()) ?>" style="margin-top:20px">
|
||||
<?= $block->getBlockHtml('formkey') ?><input type="hidden" name="customer_id" value="<?= $escaper->escapeHtmlAttr((string)$block->getCustomerId()) ?>">
|
||||
<div class="admin__field"><label class="admin__field-label"><span><?= $escaper->escapeHtml(__('Type')) ?></span></label><div class="admin__field-control"><select class="admin__control-select" name="adjustment_type"><option value="admin_adjustment"><?= $escaper->escapeHtml(__('Manual Adjustment')) ?></option><option value="social_share"><?= $escaper->escapeHtml(__('Social Media Share (%1 points)', $block->getSocialPoints())) ?></option></select></div></div>
|
||||
<div class="admin__field"><label class="admin__field-label"><span><?= $escaper->escapeHtml(__('Operation')) ?></span></label><div class="admin__field-control"><select class="admin__control-select" name="operation"><option value="add"><?= $escaper->escapeHtml(__('Add')) ?></option><option value="subtract"><?= $escaper->escapeHtml(__('Subtract')) ?></option></select></div></div>
|
||||
<div class="admin__field required"><label class="admin__field-label"><span><?= $escaper->escapeHtml(__('Points')) ?></span></label><div class="admin__field-control"><input class="admin__control-text" type="number" min="1" name="points" required></div></div>
|
||||
<div class="admin__field required"><label class="admin__field-label"><span><?= $escaper->escapeHtml(__('Reason')) ?></span></label><div class="admin__field-control"><textarea class="admin__control-textarea" name="reason" required></textarea></div></div>
|
||||
<div class="admin__field"><label class="admin__field-label"><span><?= $escaper->escapeHtml(__('Evidence URL / Note')) ?></span></label><div class="admin__field-control"><input class="admin__control-text" name="evidence"></div></div>
|
||||
<button class="action-primary" type="submit"><span><?= $escaper->escapeHtml(__('Adjust Points')) ?></span></button>
|
||||
</form>
|
||||
<h3 style="margin-top:25px"><?= $escaper->escapeHtml(__('Recent Point Changes')) ?></h3>
|
||||
<table class="data-grid"><thead><tr><th class="data-grid-th"><?= $escaper->escapeHtml(__('Date')) ?></th><th class="data-grid-th"><?= $escaper->escapeHtml(__('Type')) ?></th><th class="data-grid-th"><?= $escaper->escapeHtml(__('Change')) ?></th><th class="data-grid-th"><?= $escaper->escapeHtml(__('Balance')) ?></th><th class="data-grid-th"><?= $escaper->escapeHtml(__('Reason')) ?></th></tr></thead><tbody>
|
||||
<?php foreach ($block->getTransactions() as $row): ?><tr><td><?= $escaper->escapeHtml($row['created_at']) ?></td><td><?= $escaper->escapeHtml($row['type']) ?></td><td><?= (int)$row['points_delta'] > 0 ? '+' : '' ?><?= (int)$row['points_delta'] ?></td><td><?= (int)$row['balance_after'] ?></td><td><?= $escaper->escapeHtml((string)$row['reason']) ?></td></tr><?php endforeach; ?>
|
||||
</tbody></table>
|
||||
</div>
|
||||
</section>
|
||||
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0"?>
|
||||
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
|
||||
<head><css src="Esun_Reward::css/reward.css"/></head><body><referenceContainer name="cart.summary">
|
||||
<block class="Esun\Reward\Block\Cart\Reward" name="esun.cart.reward" template="Esun_Reward::cart/reward.phtml" after="esun.cart.coupon" before="checkout.cart.methods.bottom"/>
|
||||
</referenceContainer></body>
|
||||
</page>
|
||||
@@ -0,0 +1,55 @@
|
||||
<?xml version="1.0"?>
|
||||
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
|
||||
<head><css src="Esun_Reward::css/reward.css"/></head>
|
||||
<body>
|
||||
<referenceBlock name="checkout.root">
|
||||
<arguments>
|
||||
<argument name="jsLayout" xsi:type="array">
|
||||
<item name="components" xsi:type="array">
|
||||
<item name="checkout" xsi:type="array">
|
||||
<item name="children" xsi:type="array">
|
||||
<item name="steps" xsi:type="array">
|
||||
<item name="children" xsi:type="array">
|
||||
<item name="billing-step" xsi:type="array">
|
||||
<item name="children" xsi:type="array">
|
||||
<item name="payment" xsi:type="array">
|
||||
<item name="children" xsi:type="array">
|
||||
<item name="afterMethods" xsi:type="array">
|
||||
<item name="children" xsi:type="array">
|
||||
<item name="esun-reward" xsi:type="array">
|
||||
<item name="component" xsi:type="string">Esun_Reward/js/view/payment/reward</item>
|
||||
<item name="sortOrder" xsi:type="number">20</item>
|
||||
</item>
|
||||
</item>
|
||||
</item>
|
||||
</item>
|
||||
</item>
|
||||
</item>
|
||||
</item>
|
||||
</item>
|
||||
</item>
|
||||
<item name="sidebar" xsi:type="array">
|
||||
<item name="children" xsi:type="array">
|
||||
<item name="summary" xsi:type="array">
|
||||
<item name="children" xsi:type="array">
|
||||
<item name="totals" xsi:type="array">
|
||||
<item name="children" xsi:type="array">
|
||||
<item name="reward_discount" xsi:type="array">
|
||||
<item name="component" xsi:type="string">Esun_Reward/js/view/summary/reward-discount</item>
|
||||
<item name="sortOrder" xsi:type="number">35</item>
|
||||
</item>
|
||||
</item>
|
||||
</item>
|
||||
</item>
|
||||
</item>
|
||||
</item>
|
||||
</item>
|
||||
</item>
|
||||
</item>
|
||||
</item>
|
||||
</argument>
|
||||
</arguments>
|
||||
</referenceBlock>
|
||||
</body>
|
||||
</page>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0"?>
|
||||
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"><body><referenceBlock name="customer_account_navigation"><block class="Magento\Customer\Block\Account\SortLinkInterface" name="customer-account-navigation-reward"><arguments><argument name="path" xsi:type="string">reward/account</argument><argument name="label" xsi:type="string" translate="true">My Points</argument><argument name="sortOrder" xsi:type="number">245</argument></arguments></block></referenceBlock></body></page>
|
||||
@@ -0,0 +1,16 @@
|
||||
<?xml version="1.0"?>
|
||||
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
|
||||
<update handle="customer_account"/>
|
||||
<head>
|
||||
<css src="Esun_Customer::css/account-dashboard.css"/>
|
||||
<css src="Esun_Reward::css/reward.css"/>
|
||||
</head>
|
||||
<body>
|
||||
<referenceBlock name="page.main.title" remove="true"/>
|
||||
<referenceBlock name="catalog.compare.sidebar" remove="true"/>
|
||||
<referenceBlock name="wishlist_sidebar" remove="true"/>
|
||||
<referenceContainer name="content">
|
||||
<block class="Esun\Reward\Block\Account\Index" name="esun.reward.account" template="Esun_Reward::account/index.phtml" cacheable="false"/>
|
||||
</referenceContainer>
|
||||
</body>
|
||||
</page>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0"?>
|
||||
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"><head><css src="Esun_Reward::css/reward.css"/></head><body><referenceContainer name="content"><block class="Esun\Reward\Block\Product\ListProduct" name="esun.reward.products" template="Esun_Reward::product/list.phtml" cacheable="false"/></referenceContainer></body></page>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?xml version="1.0"?>
|
||||
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd"><body><referenceBlock name="order_totals"><block class="Esun\Reward\Block\Order\RewardTotals" name="esun.order.reward.totals"/></referenceBlock></body></page>
|
||||
@@ -0,0 +1,9 @@
|
||||
var config = {
|
||||
config: {
|
||||
mixins: {
|
||||
'Magento_SalesRule/js/view/payment/discount': {
|
||||
'Esun_Reward/js/view/payment/discount-mixin': true
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,100 @@
|
||||
<?php
|
||||
/** @var \Esun\Reward\Block\Account\Index $block */
|
||||
/** @var \Magento\Framework\Escaper $escaper */
|
||||
$account = $block->getAccount();
|
||||
$tier = $block->getTier();
|
||||
$transactions = $block->getTransactions();
|
||||
$balance = (int)($account['balance'] ?? 0);
|
||||
$lifetimeSpend = (float)($account['lifetime_spend_base'] ?? 0);
|
||||
?>
|
||||
<div class="esun-reward-account">
|
||||
<section class="esun-account-welcome esun-reward-hero">
|
||||
<i class="esun-account-avatar iconfont icon-jinbi2" aria-hidden="true"></i>
|
||||
<div class="esun-reward-hero__content">
|
||||
<h1><?= $escaper->escapeHtml(__('My Points')) ?></h1>
|
||||
<strong><?= $escaper->escapeHtml(__('Points: %1', $balance)) ?></strong>
|
||||
</div>
|
||||
<div class="esun-reward-tier">
|
||||
<span><?= $escaper->escapeHtml(__('VIP Tier')) ?></span>
|
||||
<strong><?= $escaper->escapeHtml($tier['label']) ?></strong>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="esun-account-panel esun-reward-overview">
|
||||
<header><h2><?= $escaper->escapeHtml(__('Points Overview')) ?></h2></header>
|
||||
<div class="esun-reward-account__summary">
|
||||
<article class="esun-reward-card">
|
||||
<i class="iconfont icon-jinbi2" aria-hidden="true"></i>
|
||||
<span><?= $escaper->escapeHtml(__('Available Points')) ?></span>
|
||||
<strong><?= $escaper->escapeHtml((string)$balance) ?></strong>
|
||||
</article>
|
||||
<article class="esun-reward-card">
|
||||
<i class="iconfont icon-member6" aria-hidden="true"></i>
|
||||
<span><?= $escaper->escapeHtml(__('VIP Tier')) ?></span>
|
||||
<strong><?= $escaper->escapeHtml($tier['label']) ?></strong>
|
||||
<small><?= $escaper->escapeHtml(__('%1× points', $tier['multiplier'])) ?></small>
|
||||
</article>
|
||||
<article class="esun-reward-card">
|
||||
<i class="iconfont icon-dollar1" aria-hidden="true"></i>
|
||||
<span><?= $escaper->escapeHtml(__('Lifetime Spend')) ?></span>
|
||||
<strong>$<?= $escaper->escapeHtml(number_format($lifetimeSpend, 2)) ?></strong>
|
||||
<?php if ($tier['next_threshold'] !== null): ?>
|
||||
<small>
|
||||
<?= $escaper->escapeHtml(
|
||||
__('$%1 to next tier', number_format(
|
||||
max(0, $tier['next_threshold'] - $lifetimeSpend),
|
||||
2
|
||||
))
|
||||
) ?>
|
||||
</small>
|
||||
<?php endif; ?>
|
||||
</article>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="esun-account-panel esun-reward-history-panel">
|
||||
<header><h2><?= $escaper->escapeHtml(__('Point History')) ?></h2></header>
|
||||
<?php if ($transactions): ?>
|
||||
<div class="table-wrapper">
|
||||
<table class="data table esun-reward-history">
|
||||
<thead><tr>
|
||||
<th scope="col"><?= $escaper->escapeHtml(__('Date')) ?></th>
|
||||
<th scope="col"><?= $escaper->escapeHtml(__('Activity')) ?></th>
|
||||
<th scope="col"><?= $escaper->escapeHtml(__('Change')) ?></th>
|
||||
<th scope="col"><?= $escaper->escapeHtml(__('Balance')) ?></th>
|
||||
<th scope="col"><?= $escaper->escapeHtml(__('Reason')) ?></th>
|
||||
</tr></thead>
|
||||
<tbody>
|
||||
<?php foreach ($transactions as $row): ?>
|
||||
<?php $delta = (int)$row['points_delta']; ?>
|
||||
<tr>
|
||||
<td data-th="<?= $escaper->escapeHtmlAttr(__('Date')) ?>">
|
||||
<?= $escaper->escapeHtml($row['created_at']) ?>
|
||||
</td>
|
||||
<td data-th="<?= $escaper->escapeHtmlAttr(__('Activity')) ?>">
|
||||
<?= $escaper->escapeHtml($block->getActivityName((string)$row['type'])) ?>
|
||||
</td>
|
||||
<td class="esun-reward-history__change <?= $delta >= 0
|
||||
? 'is-positive'
|
||||
: 'is-negative' ?>" data-th="<?= $escaper->escapeHtmlAttr(__('Change')) ?>">
|
||||
<?= $escaper->escapeHtml(($delta > 0 ? '+' : '') . (string)$delta) ?>
|
||||
</td>
|
||||
<td data-th="<?= $escaper->escapeHtmlAttr(__('Balance')) ?>">
|
||||
<?= $escaper->escapeHtml((string)(int)$row['balance_after']) ?>
|
||||
</td>
|
||||
<td data-th="<?= $escaper->escapeHtmlAttr(__('Reason')) ?>">
|
||||
<?= $escaper->escapeHtml((string)$row['reason']) ?>
|
||||
</td>
|
||||
</tr>
|
||||
<?php endforeach; ?>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<div class="esun-reward-empty">
|
||||
<i class="iconfont icon-jinbi2" aria-hidden="true"></i>
|
||||
<p><?= $escaper->escapeHtml(__('You have no point activity yet.')) ?></p>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</section>
|
||||
</div>
|
||||
@@ -0,0 +1,12 @@
|
||||
<?php /** @var \Esun\Reward\Block\Cart\Reward $block */ /** @var \Magento\Framework\Escaper $escaper */ ?>
|
||||
<div class="esun-coupon esun-coupon--cart esun-reward-use">
|
||||
<div class="esun-coupon__title"><?= $escaper->escapeHtml(__('Use Points')) ?></div>
|
||||
<?php if ($block->isLoggedIn()): ?>
|
||||
<p class="esun-reward-use__balance"><?= $escaper->escapeHtml(__('Available balance: %1 points', $block->getBalance())) ?></p>
|
||||
<form data-role="esun-reward-form" data-url="<?= $escaper->escapeUrl($block->getApplyUrl()) ?>">
|
||||
<?= $block->getBlockHtml('formkey') ?><div class="esun-coupon__controls"><label class="esun-coupon__label" for="esun-cart-reward-points"><?= $escaper->escapeHtml(__('Points to use')) ?></label><input id="esun-cart-reward-points" class="input-text esun-coupon__input" type="number" name="points" min="0" max="<?= $escaper->escapeHtmlAttr((string)min($block->getMaximum(), $block->getBalance())) ?>" value="<?= $escaper->escapeHtmlAttr((string)$block->getAppliedPoints()) ?>"><button class="action esun-coupon__button" type="submit"><span><?= $escaper->escapeHtml(__('Apply')) ?></span></button></div>
|
||||
<p class="note"><?= $escaper->escapeHtml(__('%1 points = $1. Maximum %2 points per order.', $block->getRate(), $block->getMaximum())) ?></p><div data-role="esun-reward-message"></div>
|
||||
</form>
|
||||
<?php else: ?><p><a href="<?= $escaper->escapeUrl($block->getUrl('customer/account/login')) ?>"><?= $escaper->escapeHtml(__('Sign in to view and use your points.')) ?></a></p><?php endif; ?>
|
||||
</div>
|
||||
<script type="text/x-magento-init">{"[data-role=esun-reward-form]":{"Esun_Reward/js/reward-form":{}}}</script>
|
||||
@@ -0,0 +1,2 @@
|
||||
<?php /** @var \Esun\Reward\Block\Product\ListProduct $block */ /** @var \Magento\Framework\Escaper $escaper */ ?>
|
||||
<div class="esun-reward-products"><p><?= $escaper->escapeHtml(__('Your points: %1', $block->getBalance())) ?></p><div class="products wrapper grid products-grid"><ol class="products list items product-items"><?php foreach($block->getProducts() as $product):?><li class="item product product-item"><div class="product-item-info"><a class="product photo product-item-photo" href="<?= $escaper->escapeUrl($product->getProductUrl()) ?>"><img class="product-image-photo" src="<?= $escaper->escapeUrl($block->getImageUrl($product)) ?>" alt="<?= $escaper->escapeHtmlAttr($product->getName()) ?>"></a><div class="product details product-item-details"><strong class="product name product-item-name"><?= $escaper->escapeHtml($product->getName()) ?></strong><div class="price-box"><strong><?= (int)$product->getData('reward_points_cost') ?> <?= $escaper->escapeHtml(__('points')) ?></strong></div><?php if($block->isLoggedIn()&&$product->getTypeId()==='simple'):?><form method="post" action="<?= $escaper->escapeUrl($block->getRedeemUrl()) ?>"><?= $block->getBlockHtml('formkey') ?><input type="hidden" name="product_id" value="<?= (int)$product->getId() ?>"><button class="action primary" type="submit" <?= $block->getBalance()<(int)$product->getData('reward_points_cost')?'disabled':'' ?>><span><?= $escaper->escapeHtml(__('Redeem')) ?></span></button></form><?php endif;?></div></div></li><?php endforeach;?></ol></div></div>
|
||||
@@ -0,0 +1,379 @@
|
||||
.esun-reward-use {
|
||||
border: 1px solid #ddd;
|
||||
margin: 16px 0;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.esun-reward-use .action,
|
||||
.esun-reward-products .action.primary,
|
||||
.esun-coupon__button {
|
||||
background: #18aa59;
|
||||
background-image: none;
|
||||
border-color: #18aa59;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.esun-reward-use .action:hover,
|
||||
.esun-reward-use .action:focus,
|
||||
.esun-reward-products .action.primary:hover,
|
||||
.esun-reward-products .action.primary:focus,
|
||||
.esun-coupon__button:hover,
|
||||
.esun-coupon__button:focus {
|
||||
background: #148f4b;
|
||||
background-image: none;
|
||||
border-color: #148f4b;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.esun-reward-use__title {
|
||||
font-weight: 700;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.esun-reward-use__controls {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.esun-reward-use__controls input {
|
||||
max-width: 180px;
|
||||
}
|
||||
|
||||
.checkout-index-index .amcheckout-summary-container .esun-checkout-summary-tool,
|
||||
.checkout-index-index .amcheckout-summary-container .esun-reward-use {
|
||||
background: #fff;
|
||||
border: 1px solid #d8dcde;
|
||||
border-radius: 14px;
|
||||
margin: 12px 0;
|
||||
padding: 18px 20px;
|
||||
}
|
||||
|
||||
.checkout-index-index .amcheckout-summary-container .esun-coupon__title {
|
||||
color: #292d30;
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
margin-bottom: 11px;
|
||||
}
|
||||
|
||||
.checkout-index-index .amcheckout-summary-container .esun-coupon__label {
|
||||
clip: rect(0, 0, 0, 0);
|
||||
height: 1px;
|
||||
overflow: hidden;
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
}
|
||||
|
||||
.checkout-index-index .amcheckout-summary-container .esun-coupon__controls {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.checkout-index-index .amcheckout-summary-container .esun-coupon__input {
|
||||
flex: 1 1 auto;
|
||||
height: 46px;
|
||||
min-width: 0;
|
||||
max-width: none;
|
||||
border: 1px solid #cfd4d7;
|
||||
border-radius: 23px;
|
||||
padding: 0 18px;
|
||||
}
|
||||
|
||||
.checkout-index-index .amcheckout-summary-container .esun-coupon__button {
|
||||
background: #fff;
|
||||
border: 1px solid #18aa59;
|
||||
border-radius: 23px;
|
||||
color: #168b4b;
|
||||
flex: 0 0 auto;
|
||||
font-weight: 700;
|
||||
height: 46px;
|
||||
min-width: 96px;
|
||||
padding: 0 20px;
|
||||
}
|
||||
|
||||
.checkout-index-index .amcheckout-summary-container .esun-coupon__button:hover,
|
||||
.checkout-index-index .amcheckout-summary-container .esun-coupon__button:focus {
|
||||
background: #148f4b;
|
||||
border-color: #148f4b;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.checkout-index-index .amcheckout-summary-container .esun-coupon__picker-button {
|
||||
font-size: 14px;
|
||||
grid-column: 1 / -1;
|
||||
justify-self: end;
|
||||
min-width: 0;
|
||||
height: auto;
|
||||
margin-top: 2px;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.checkout-index-index .amcheckout-summary-container .esun-coupon__applied {
|
||||
align-items: center;
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 16px;
|
||||
min-height: 42px;
|
||||
}
|
||||
|
||||
.checkout-index-index
|
||||
.amcheckout-summary-container
|
||||
.esun-coupon__applied
|
||||
.esun-coupon__picker-button {
|
||||
grid-column: 1 / -1;
|
||||
justify-self: end;
|
||||
}
|
||||
|
||||
.checkout-index-index .amcheckout-summary-container .esun-coupon__applied strong {
|
||||
color: #168b4b;
|
||||
}
|
||||
|
||||
.checkout-index-index .amcheckout-summary-container .esun-coupon__applied > span {
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.checkout-index-index .amcheckout-summary-container .esun-coupon__remove {
|
||||
background: transparent !important;
|
||||
border: 0 !important;
|
||||
border-radius: 0 !important;
|
||||
box-shadow: none !important;
|
||||
color: #168b4b;
|
||||
height: auto !important;
|
||||
margin: 0 !important;
|
||||
min-height: 0 !important;
|
||||
min-width: 0 !important;
|
||||
padding: 0 !important;
|
||||
text-decoration: underline;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.checkout-index-index .amcheckout-summary-container .esun-coupon__message {
|
||||
display: none;
|
||||
font-size: 13px;
|
||||
margin-top: 9px;
|
||||
}
|
||||
|
||||
.checkout-index-index .amcheckout-summary-container .esun-coupon__message.is-error,
|
||||
.checkout-index-index .amcheckout-summary-container .esun-coupon__message.is-success {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.checkout-index-index .amcheckout-summary-container .esun-coupon__message.is-error {
|
||||
color: #c62828;
|
||||
}
|
||||
|
||||
.checkout-index-index .amcheckout-summary-container .esun-coupon__message.is-success {
|
||||
color: #168b4b;
|
||||
}
|
||||
|
||||
.checkout-index-index .amcheckout-summary-container .esun-reward-use__balance {
|
||||
margin: 0 0 10px;
|
||||
}
|
||||
|
||||
.checkout-index-index .amcheckout-summary-container .esun-reward-use .note {
|
||||
margin: 8px 0 0;
|
||||
}
|
||||
|
||||
.esun-reward-account {
|
||||
color: #333;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.esun-reward-hero .esun-account-avatar {
|
||||
color: #aaa;
|
||||
font-size: 82px;
|
||||
}
|
||||
|
||||
.esun-reward-hero__content {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.esun-reward-tier {
|
||||
background: #050505;
|
||||
border-radius: 30px;
|
||||
color: #fff;
|
||||
margin-left: auto;
|
||||
min-width: 180px;
|
||||
padding: 11px 30px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.esun-reward-tier > span {
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
letter-spacing: .08em;
|
||||
line-height: 1.2;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.esun-reward-tier > strong {
|
||||
color: #fff;
|
||||
font-size: 23px;
|
||||
line-height: 1.25;
|
||||
}
|
||||
|
||||
.esun-reward-overview,
|
||||
.esun-reward-history-panel {
|
||||
padding: 38px 34px;
|
||||
}
|
||||
|
||||
.esun-reward-account__summary {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||
margin-top: 30px;
|
||||
}
|
||||
|
||||
.esun-reward-card {
|
||||
align-items: center;
|
||||
background: #fafafa;
|
||||
box-sizing: border-box;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-height: 190px;
|
||||
padding: 27px 20px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.esun-reward-card + .esun-reward-card {
|
||||
border-left: 1px solid #e2e2e2;
|
||||
}
|
||||
|
||||
.esun-reward-card > .iconfont {
|
||||
color: #666;
|
||||
font-size: 42px;
|
||||
height: 48px;
|
||||
line-height: 48px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.esun-reward-card > span {
|
||||
color: #777;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.esun-reward-card > strong {
|
||||
color: #222;
|
||||
display: block;
|
||||
font-size: 25px;
|
||||
font-weight: 600;
|
||||
line-height: 1.25;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.esun-reward-card:first-child > strong {
|
||||
color: #f28c00;
|
||||
}
|
||||
|
||||
.esun-reward-card > small {
|
||||
color: #888;
|
||||
display: block;
|
||||
font-size: 13px;
|
||||
margin-top: 5px;
|
||||
}
|
||||
|
||||
.esun-reward-history-panel .table-wrapper {
|
||||
margin-top: 30px;
|
||||
overflow-x: auto;
|
||||
}
|
||||
|
||||
.esun-reward-history {
|
||||
border-collapse: collapse;
|
||||
margin: 0;
|
||||
min-width: 720px;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.esun-reward-history thead {
|
||||
background: #fafafa;
|
||||
}
|
||||
|
||||
.esun-reward-history th,
|
||||
.esun-reward-history td {
|
||||
border-bottom: 1px solid #e6e6e6;
|
||||
padding: 16px 18px;
|
||||
text-align: left;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
.esun-reward-history th {
|
||||
color: #666;
|
||||
font-size: 14px;
|
||||
font-weight: 500;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.esun-reward-history td {
|
||||
color: #444;
|
||||
font-size: 15px;
|
||||
}
|
||||
|
||||
.esun-reward-history tbody tr:hover {
|
||||
background: #fcfcfc;
|
||||
}
|
||||
|
||||
.esun-reward-history__change {
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.esun-reward-history__change.is-positive {
|
||||
color: #299b59;
|
||||
}
|
||||
|
||||
.esun-reward-history__change.is-negative {
|
||||
color: #e45752;
|
||||
}
|
||||
|
||||
.esun-reward-empty {
|
||||
color: #888;
|
||||
padding: 48px 20px 30px;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.esun-reward-empty .iconfont {
|
||||
color: #aaa;
|
||||
display: block;
|
||||
font-size: 58px;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.esun-reward-empty p {
|
||||
margin: 14px 0 0;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.esun-reward-account__summary {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.esun-reward-card {
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.esun-reward-card + .esun-reward-card {
|
||||
border-left: 0;
|
||||
border-top: 1px solid #e2e2e2;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.esun-reward-tier {
|
||||
margin-left: 0;
|
||||
min-width: 0;
|
||||
padding: 9px 22px;
|
||||
}
|
||||
|
||||
.esun-reward-tier > strong {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.esun-reward-overview,
|
||||
.esun-reward-history-panel {
|
||||
padding: 24px 18px;
|
||||
}
|
||||
|
||||
.esun-reward-account__summary,
|
||||
.esun-reward-history-panel .table-wrapper {
|
||||
margin-top: 20px;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
define(['jquery', 'mage/url', 'mage/cookies'], function ($, urlBuilder) {
|
||||
'use strict';
|
||||
return { apply: function (points) { return $.ajax({url: urlBuilder.build('reward/cart/apply'), type: 'POST', dataType: 'json', data: {form_key: $.mage.cookies.get('form_key'), points: points}}); } };
|
||||
});
|
||||
@@ -0,0 +1,12 @@
|
||||
define(['jquery', 'mage/translate', 'Magento_Customer/js/customer-data'], function ($, $t, customerData) {
|
||||
'use strict';
|
||||
return function (config, element) {
|
||||
$(element).on('submit', function (event) {
|
||||
event.preventDefault(); var $form = $(this), $message = $form.find('[data-role=esun-reward-message]');
|
||||
$.ajax({url: $form.data('url'), type: 'POST', dataType: 'json', data: $form.serialize(), showLoader: true})
|
||||
.done(function (response) { $message.text(response.message || ''); customerData.reload(['cart'], true).always(function () { window.location.reload(); }); })
|
||||
.fail(function (xhr) { $message.text((xhr.responseJSON && xhr.responseJSON.message) || $t('Unable to apply points.')); });
|
||||
return false;
|
||||
});
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
define([
|
||||
'jquery',
|
||||
'Magento_Checkout/js/action/get-totals',
|
||||
'Magento_Customer/js/customer-data'
|
||||
], function ($, getTotalsAction, customerData) {
|
||||
'use strict';
|
||||
|
||||
return function (Discount) {
|
||||
return Discount.extend({
|
||||
initialize: function () {
|
||||
this._super();
|
||||
$(document)
|
||||
.off('esun:customerCouponApplied.esunCheckoutDiscount')
|
||||
.on('esun:customerCouponApplied.esunCheckoutDiscount',
|
||||
this.onCustomerCouponApplied.bind(this));
|
||||
|
||||
return this;
|
||||
},
|
||||
|
||||
onCustomerCouponApplied: function (event, response) {
|
||||
var code = response && response.coupon_code || '';
|
||||
|
||||
this.couponCode(code);
|
||||
this.isApplied(Boolean(code));
|
||||
customerData.reload(['cart'], true);
|
||||
getTotalsAction([]);
|
||||
}
|
||||
});
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
define([
|
||||
'uiComponent',
|
||||
'ko',
|
||||
'jquery',
|
||||
'mage/translate',
|
||||
'mage/url',
|
||||
'Magento_Customer/js/customer-data',
|
||||
'Esun_Reward/js/model/reward-service',
|
||||
'Magento_Checkout/js/action/get-totals'
|
||||
], function (Component, ko, $, $t, urlBuilder, customerData, rewardService, getTotalsAction) {
|
||||
'use strict';
|
||||
return Component.extend({
|
||||
defaults: {template: 'Esun_Reward/payment/reward'},
|
||||
initialize: function () {
|
||||
var self = this,
|
||||
checkoutReward = window.checkoutConfig.esunReward || {},
|
||||
cartReward;
|
||||
|
||||
this._super();
|
||||
this.cart = customerData.get('cart');
|
||||
this.customer = customerData.get('customer');
|
||||
cartReward = this.cart().reward || {};
|
||||
this.rewardData = ko.observable($.extend({
|
||||
logged_in: false,
|
||||
balance: 0,
|
||||
applied_points: 0,
|
||||
maximum: 1500,
|
||||
rate: 100
|
||||
}, cartReward, checkoutReward));
|
||||
this.points = ko.observable(Number(this.rewardData().applied_points || 0));
|
||||
this.message = ko.observable('');
|
||||
this.loading = ko.observable(false);
|
||||
this.ready = ko.observable(false);
|
||||
this.cart.subscribe(function (cart) {
|
||||
if (cart.reward) {
|
||||
self.rewardData(cart.reward);
|
||||
}
|
||||
});
|
||||
this.refreshRewardData();
|
||||
return this;
|
||||
},
|
||||
reward: function () { return this.rewardData(); },
|
||||
isLoggedIn: function () {
|
||||
var customer = this.customer();
|
||||
|
||||
return Boolean(this.reward().logged_in || customer.fullname || customer.firstname);
|
||||
},
|
||||
refreshRewardData: function () {
|
||||
var self = this;
|
||||
|
||||
$.ajax({
|
||||
url: urlBuilder.build('customer/section/load/'),
|
||||
type: 'get',
|
||||
dataType: 'json',
|
||||
cache: false,
|
||||
data: {
|
||||
sections: 'cart,customer',
|
||||
force_new_section_timestamp: true
|
||||
}
|
||||
}).done(function (sections) {
|
||||
if (sections.cart) {
|
||||
customerData.set('cart', sections.cart);
|
||||
if (sections.cart.reward) {
|
||||
self.rewardData(sections.cart.reward);
|
||||
}
|
||||
self.points(Number((sections.cart.reward || {}).applied_points || 0));
|
||||
}
|
||||
if (sections.customer) {
|
||||
customerData.set('customer', sections.customer);
|
||||
}
|
||||
}).always(function () {
|
||||
self.ready(true);
|
||||
});
|
||||
},
|
||||
apply: function () { var self = this; if (this.loading()) { return false; } this.loading(true); rewardService.apply(Math.max(0, parseInt(this.points(), 10) || 0)).done(function (response) { self.message(response.message || ''); customerData.reload(['cart'], true); getTotalsAction([]); }).fail(function (xhr) { self.message((xhr.responseJSON && xhr.responseJSON.message) || $t('Unable to apply points.')); }).always(function () { self.loading(false); }); return false; }
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,26 @@
|
||||
define(['Magento_Checkout/js/view/summary/abstract-total', 'Magento_Checkout/js/model/quote'], function (Component, quote) {
|
||||
'use strict';
|
||||
return Component.extend({
|
||||
defaults: {template: 'Esun_Reward/summary/reward-discount'},
|
||||
getSegment: function () {
|
||||
var totals = quote.getTotals()();
|
||||
return totals && totals.total_segments && totals.total_segments.filter(function (item) {
|
||||
return item.code === 'reward_discount';
|
||||
})[0];
|
||||
},
|
||||
isDisplayed: function () {
|
||||
return this.getPureValue() !== 0;
|
||||
},
|
||||
getPureValue: function () {
|
||||
var segment = this.getSegment();
|
||||
return segment ? Number(segment.value) : 0;
|
||||
},
|
||||
getTitle: function () {
|
||||
var segment = this.getSegment();
|
||||
return segment && segment.title ? segment.title : this.title;
|
||||
},
|
||||
getValue: function () {
|
||||
return this.getFormattedPrice(this.getPureValue());
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
<div class="esun-coupon esun-coupon--cart esun-reward-use">
|
||||
<div class="esun-coupon__title" data-bind="i18n: 'Use Points'"></div>
|
||||
<!-- ko if: ready -->
|
||||
<!-- ko if: isLoggedIn -->
|
||||
<p class="esun-reward-use__balance">
|
||||
<span data-bind="i18n: 'Available balance:'"></span>
|
||||
<strong data-bind="text: reward().balance"></strong>
|
||||
<span data-bind="i18n: 'points'"></span>
|
||||
</p>
|
||||
<form data-bind="submit: apply">
|
||||
<div class="esun-coupon__controls">
|
||||
<label class="esun-coupon__label" for="esun-checkout-reward-points"
|
||||
data-bind="i18n: 'Points to use'"></label>
|
||||
<input id="esun-checkout-reward-points"
|
||||
class="input-text esun-coupon__input"
|
||||
type="number"
|
||||
min="0"
|
||||
data-bind="value: points,
|
||||
attr: {max: Math.min(Number(reward().balance), Number(reward().maximum))},
|
||||
disable: loading"/>
|
||||
<button class="action esun-coupon__button" type="submit" data-bind="disable: loading">
|
||||
<span data-bind="i18n: 'Apply'"></span>
|
||||
</button>
|
||||
</div>
|
||||
<p class="note">
|
||||
<span data-bind="text: reward().rate"></span>
|
||||
<span data-bind="i18n: 'points = $1. Maximum'"></span>
|
||||
<span data-bind="text: reward().maximum"></span>
|
||||
<span data-bind="i18n: 'points per order.'"></span>
|
||||
</p>
|
||||
<div class="esun-coupon__message"
|
||||
data-bind="text: message, css: {'is-success': message()}"></div>
|
||||
</form>
|
||||
<!-- /ko -->
|
||||
<!-- ko ifnot: isLoggedIn -->
|
||||
<p><a data-bind="attr: {href: window.BASE_URL + 'customer/account/login/'},
|
||||
i18n: 'Sign in to view and use your points.'"></a></p>
|
||||
<!-- /ko -->
|
||||
<!-- /ko -->
|
||||
</div>
|
||||
@@ -0,0 +1,6 @@
|
||||
<!-- ko if: isDisplayed() -->
|
||||
<tr class="totals reward-discount">
|
||||
<th class="mark" scope="row"><span data-bind="text: getTitle()"></span></th>
|
||||
<td class="amount"><span class="price" data-bind="text: getValue()"></span></td>
|
||||
</tr>
|
||||
<!-- /ko -->
|
||||
Reference in New Issue
Block a user