init
This commit is contained in:
@@ -0,0 +1,9 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Api;
|
||||
|
||||
interface CouponNotifierInterface
|
||||
{
|
||||
public function notify(int $assignmentId): void;
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Block\Account;
|
||||
|
||||
use Esun\CustomerCoupon\Model\Coupon\ListProvider;
|
||||
use Magento\Customer\Model\Session as CustomerSession;
|
||||
use Magento\Framework\View\Element\Template;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class Coupons extends Template
|
||||
{
|
||||
private ?array $coupons = null;
|
||||
|
||||
public function __construct(
|
||||
Template\Context $context,
|
||||
private readonly CustomerSession $customerSession,
|
||||
private readonly StoreManagerInterface $storeManager,
|
||||
private readonly ListProvider $listProvider,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function getAvailableCoupons(): array
|
||||
{
|
||||
return array_values(array_filter(
|
||||
$this->getCoupons(),
|
||||
static fn(array $coupon): bool => $coupon['status'] === 'available'
|
||||
));
|
||||
}
|
||||
|
||||
public function getUnavailableCoupons(): array
|
||||
{
|
||||
return array_values(array_filter(
|
||||
$this->getCoupons(),
|
||||
static fn(array $coupon): bool => $coupon['status'] !== 'available'
|
||||
));
|
||||
}
|
||||
|
||||
private function getCoupons(): array
|
||||
{
|
||||
if ($this->coupons === null) {
|
||||
$this->coupons = $this->listProvider->getForCustomer(
|
||||
(int)$this->customerSession->getCustomerId(),
|
||||
(int)$this->storeManager->getStore()->getWebsiteId(),
|
||||
(int)$this->customerSession->getCustomerGroupId()
|
||||
);
|
||||
}
|
||||
|
||||
return $this->coupons;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Block\Adminhtml\Form;
|
||||
|
||||
use Magento\Backend\Block\Template;
|
||||
use Magento\Framework\Registry;
|
||||
use Magento\SalesRule\Model\RegistryConstants;
|
||||
|
||||
class CustomerSelect extends Template
|
||||
{
|
||||
public function __construct(
|
||||
Template\Context $context,
|
||||
private readonly Registry $registry,
|
||||
array $data = []
|
||||
) {
|
||||
parent::__construct($context, $data);
|
||||
}
|
||||
|
||||
public function getSearchUrl(): string
|
||||
{
|
||||
$rule = $this->registry->registry(RegistryConstants::CURRENT_SALES_RULE);
|
||||
|
||||
return $this->getUrl('esun_customer_coupon/customer/search', [
|
||||
'rule_id' => $rule ? (int)$rule->getId() : 0,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Block\Adminhtml\Promo\Quote\Edit\Tab\Coupons;
|
||||
|
||||
use Magento\Framework\Data\Collection;
|
||||
use Magento\Framework\Data\Collection\AbstractDb;
|
||||
|
||||
class Grid extends \Magento\SalesRule\Block\Adminhtml\Promo\Quote\Edit\Tab\Coupons\Grid
|
||||
{
|
||||
public function setCollection($collection)
|
||||
{
|
||||
if ($collection instanceof AbstractDb && !$collection->getFlag('esun_customer_coupon_joined')) {
|
||||
// Keep rule_id out of the joined relation. The core coupon collection adds an
|
||||
// unqualified `rule_id` condition before the grid receives the collection.
|
||||
$assignmentSelect = $collection->getConnection()->select()
|
||||
->from(
|
||||
$collection->getTable('esun_customer_coupon'),
|
||||
['coupon_id', 'customer_id']
|
||||
);
|
||||
$collection->getSelect()
|
||||
->joinLeft(
|
||||
['customer_coupon_assignment' => $assignmentSelect],
|
||||
'main_table.coupon_id = customer_coupon_assignment.coupon_id',
|
||||
['assigned_customer_id' => 'customer_id']
|
||||
)
|
||||
->joinLeft(
|
||||
['assigned_customer' => $collection->getTable('customer_entity')],
|
||||
'customer_coupon_assignment.customer_id = assigned_customer.entity_id',
|
||||
[
|
||||
'assigned_customer_name' => new \Zend_Db_Expr(
|
||||
"TRIM(CONCAT(COALESCE(assigned_customer.firstname, ''), ' ', "
|
||||
. "COALESCE(assigned_customer.lastname, '')))"
|
||||
),
|
||||
'assigned_customer_email' => 'email',
|
||||
]
|
||||
);
|
||||
$collection->setFlag('esun_customer_coupon_joined', true);
|
||||
}
|
||||
|
||||
return parent::setCollection($collection);
|
||||
}
|
||||
|
||||
protected function _prepareColumns()
|
||||
{
|
||||
parent::_prepareColumns();
|
||||
|
||||
$this->addColumnAfter(
|
||||
'assigned_customer_name',
|
||||
[
|
||||
'header' => __('Assigned Customer'),
|
||||
'index' => 'assigned_customer_name',
|
||||
'filter_condition_callback' => [$this, 'filterAssignedCustomer'],
|
||||
'renderer' => \Esun\CustomerCoupon\Block\Adminhtml\Promo\Quote\Edit\Tab\Coupons\Grid\CustomerRenderer::class,
|
||||
],
|
||||
'code'
|
||||
);
|
||||
$this->addColumnAfter(
|
||||
'assigned_customer_email',
|
||||
[
|
||||
'header' => __('Customer Email'),
|
||||
'index' => 'assigned_customer_email',
|
||||
'filter_condition_callback' => [$this, 'filterCustomerEmail'],
|
||||
],
|
||||
'assigned_customer_name'
|
||||
);
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
public function filterAssignedCustomer(AbstractDb $collection, $column): void
|
||||
{
|
||||
$value = trim((string)$column->getFilter()->getValue());
|
||||
if ($value === '') {
|
||||
return;
|
||||
}
|
||||
|
||||
$connection = $collection->getConnection();
|
||||
$like = '%' . $value . '%';
|
||||
$conditions = [
|
||||
$connection->quoteInto('assigned_customer.firstname LIKE ?', $like),
|
||||
$connection->quoteInto('assigned_customer.lastname LIKE ?', $like),
|
||||
];
|
||||
if (ctype_digit($value)) {
|
||||
$conditions[] = $connection->quoteInto('assigned_customer.entity_id = ?', (int)$value);
|
||||
}
|
||||
$collection->getSelect()->where(implode(' OR ', $conditions));
|
||||
}
|
||||
|
||||
public function filterCustomerEmail(AbstractDb $collection, $column): void
|
||||
{
|
||||
$value = trim((string)$column->getFilter()->getValue());
|
||||
if ($value !== '') {
|
||||
$collection->getSelect()->where('assigned_customer.email LIKE ?', '%' . $value . '%');
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Block\Adminhtml\Promo\Quote\Edit\Tab\Coupons\Grid;
|
||||
|
||||
use Magento\Backend\Block\Widget\Grid\Column\Renderer\AbstractRenderer;
|
||||
use Magento\Framework\DataObject;
|
||||
|
||||
class CustomerRenderer extends AbstractRenderer
|
||||
{
|
||||
public function render(DataObject $row): string
|
||||
{
|
||||
if (!$row->getData('assigned_customer_id')) {
|
||||
return '—';
|
||||
}
|
||||
|
||||
$name = trim((string)$row->getData('assigned_customer_name')) ?: (string)__('Customer');
|
||||
|
||||
return $this->_escaper->escapeHtml($name) . ' (#' . (int)$row->getData('assigned_customer_id') . ')';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Controller\Account;
|
||||
|
||||
use Magento\Customer\Controller\AbstractAccount;
|
||||
use Magento\Framework\App\Action\Context;
|
||||
use Magento\Framework\App\Action\HttpGetActionInterface;
|
||||
use Magento\Framework\View\Result\Page;
|
||||
use Magento\Framework\View\Result\PageFactory;
|
||||
|
||||
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 Coupons'));
|
||||
|
||||
return $page;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Controller\Adminhtml\Customer;
|
||||
|
||||
use Magento\Backend\App\Action;
|
||||
use Magento\Backend\App\Action\Context;
|
||||
use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory;
|
||||
use Magento\Framework\Controller\Result\Json;
|
||||
use Magento\Framework\Controller\Result\JsonFactory;
|
||||
use Magento\SalesRule\Model\RuleFactory;
|
||||
|
||||
class Search extends Action
|
||||
{
|
||||
public const ADMIN_RESOURCE = 'Magento_SalesRule::quote';
|
||||
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly JsonFactory $jsonFactory,
|
||||
private readonly CollectionFactory $customerCollectionFactory,
|
||||
private readonly RuleFactory $ruleFactory
|
||||
) {
|
||||
parent::__construct($context);
|
||||
}
|
||||
|
||||
public function execute(): Json
|
||||
{
|
||||
$searchKey = trim((string)$this->getRequest()->getParam('searchKey', ''));
|
||||
$page = max(1, (int)$this->getRequest()->getParam('page', 1));
|
||||
$limit = min(50, max(1, (int)$this->getRequest()->getParam('limit', 20)));
|
||||
$ruleId = (int)$this->getRequest()->getParam('rule_id');
|
||||
|
||||
$collection = $this->customerCollectionFactory->create();
|
||||
$collection->addAttributeToSelect(['firstname', 'lastname', 'email']);
|
||||
|
||||
if ($ruleId) {
|
||||
$rule = $this->ruleFactory->create()->load($ruleId);
|
||||
if ($rule->getId()) {
|
||||
$collection->addFieldToFilter('website_id', ['in' => array_map('intval', $rule->getWebsiteIds())]);
|
||||
$collection->addFieldToFilter('group_id', ['in' => array_map('intval', $rule->getCustomerGroupIds())]);
|
||||
}
|
||||
}
|
||||
|
||||
if ($searchKey !== '') {
|
||||
$like = '%' . addcslashes($searchKey, '%_') . '%';
|
||||
$conditions = [
|
||||
['attribute' => 'email', 'like' => $like],
|
||||
['attribute' => 'firstname', 'like' => $like],
|
||||
['attribute' => 'lastname', 'like' => $like],
|
||||
];
|
||||
if (ctype_digit($searchKey)) {
|
||||
$conditions[] = ['attribute' => 'entity_id', 'eq' => (int)$searchKey];
|
||||
}
|
||||
$collection->addAttributeToFilter($conditions, null, 'left');
|
||||
}
|
||||
|
||||
$collection->setOrder('entity_id', 'DESC')->setPageSize($limit)->setCurPage($page);
|
||||
$options = [];
|
||||
foreach ($collection as $customer) {
|
||||
$name = trim((string)$customer->getFirstname() . ' ' . (string)$customer->getLastname());
|
||||
$options[] = [
|
||||
'value' => (int)$customer->getId(),
|
||||
'label' => sprintf('%s <%s> (#%d)', $name ?: __('Customer'), $customer->getEmail(), $customer->getId()),
|
||||
'path' => '',
|
||||
'level' => 0,
|
||||
];
|
||||
}
|
||||
|
||||
return $this->jsonFactory->create()->setData([
|
||||
'options' => $options,
|
||||
'total' => (int)$collection->getSize(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Controller\Ajax;
|
||||
|
||||
use Esun\CustomerCoupon\Model\Coupon\ListProvider;
|
||||
use Magento\Checkout\Model\Session as CheckoutSession;
|
||||
use Magento\Customer\Model\Session as CustomerSession;
|
||||
use Magento\Framework\App\Action\Action;
|
||||
use Magento\Framework\App\Action\Context;
|
||||
use Magento\Framework\App\Action\HttpGetActionInterface;
|
||||
use Magento\Framework\Controller\Result\Json;
|
||||
use Magento\Framework\Controller\Result\JsonFactory;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class ListAction extends Action implements HttpGetActionInterface
|
||||
{
|
||||
public function __construct(
|
||||
Context $context,
|
||||
private readonly JsonFactory $jsonFactory,
|
||||
private readonly CustomerSession $customerSession,
|
||||
private readonly CheckoutSession $checkoutSession,
|
||||
private readonly StoreManagerInterface $storeManager,
|
||||
private readonly ListProvider $listProvider
|
||||
) {
|
||||
parent::__construct($context);
|
||||
}
|
||||
|
||||
public function execute(): Json
|
||||
{
|
||||
$result = $this->jsonFactory->create();
|
||||
if (!$this->customerSession->isLoggedIn()) {
|
||||
return $result->setHttpResponseCode(401)->setData([
|
||||
'success' => false,
|
||||
'message' => (string)__('Please sign in to view your coupons.'),
|
||||
]);
|
||||
}
|
||||
|
||||
$quote = $this->checkoutSession->getQuote();
|
||||
$coupons = $this->listProvider->getForCustomer(
|
||||
(int)$this->customerSession->getCustomerId(),
|
||||
(int)$this->storeManager->getStore()->getWebsiteId(),
|
||||
(int)$this->customerSession->getCustomerGroupId(),
|
||||
$quote
|
||||
);
|
||||
$coupons = array_values(array_filter(
|
||||
$coupons,
|
||||
static fn(array $coupon): bool => $coupon['status'] === 'available' && $coupon['cart_applicable']
|
||||
));
|
||||
|
||||
return $result->setData([
|
||||
'success' => true,
|
||||
'current_coupon_code' => (string)$quote->getCouponCode(),
|
||||
'coupons' => $coupons,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Model;
|
||||
|
||||
use Magento\Framework\Model\AbstractModel;
|
||||
|
||||
class Assignment extends AbstractModel
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(\Esun\CustomerCoupon\Model\ResourceModel\Assignment::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Model;
|
||||
|
||||
use Esun\CustomerCoupon\Api\CouponNotifierInterface;
|
||||
use Esun\CustomerCoupon\Model\ResourceModel\Assignment as AssignmentResource;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\SalesRule\Model\CouponFactory;
|
||||
|
||||
class AssignmentService
|
||||
{
|
||||
public function __construct(
|
||||
private readonly AssignmentFactory $assignmentFactory,
|
||||
private readonly AssignmentResource $assignmentResource,
|
||||
private readonly CouponFactory $couponFactory,
|
||||
private readonly CouponNotifierInterface $couponNotifier
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Assign generated coupon codes to customers.
|
||||
*
|
||||
* @param string[] $codes
|
||||
* @param int[] $customerIds
|
||||
* @param int $ruleId
|
||||
* @param string|null $source Stable source key used to make automatic grants idempotent
|
||||
*/
|
||||
public function assignCodes(array $codes, array $customerIds, int $ruleId, ?string $source = null): void
|
||||
{
|
||||
if (count($codes) !== count($customerIds)) {
|
||||
throw new LocalizedException(__('The generated coupon count does not match the selected customer count.'));
|
||||
}
|
||||
|
||||
$connection = $this->assignmentResource->getConnection();
|
||||
$assignmentIds = [];
|
||||
$connection->beginTransaction();
|
||||
try {
|
||||
foreach (array_values($codes) as $index => $code) {
|
||||
$coupon = $this->couponFactory->create()->load($code, 'code');
|
||||
if (!$coupon->getId()) {
|
||||
throw new LocalizedException(__('The generated coupon "%1" could not be loaded.', $code));
|
||||
}
|
||||
|
||||
$assignment = $this->assignmentFactory->create();
|
||||
$assignment->setData([
|
||||
'coupon_id' => (int)$coupon->getId(),
|
||||
'rule_id' => $ruleId,
|
||||
'customer_id' => (int)$customerIds[$index],
|
||||
'source' => $source,
|
||||
]);
|
||||
$this->assignmentResource->save($assignment);
|
||||
$assignmentIds[] = (int)$assignment->getId();
|
||||
}
|
||||
$connection->commit();
|
||||
} catch (\Throwable $exception) {
|
||||
$connection->rollBack();
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
foreach ($assignmentIds as $assignmentId) {
|
||||
try {
|
||||
$this->couponNotifier->notify($assignmentId);
|
||||
} catch (\Throwable) {
|
||||
// Notification delivery is best-effort and must not invalidate an assigned coupon.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Model;
|
||||
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
use Magento\Store\Model\ScopeInterface;
|
||||
|
||||
class Config
|
||||
{
|
||||
private const XML_PATH_REGISTRATION_SUBSCRIPTION_RULE =
|
||||
'esun_customer_coupon/registration_subscription/rule_id';
|
||||
|
||||
public function __construct(private readonly ScopeConfigInterface $scopeConfig)
|
||||
{
|
||||
}
|
||||
|
||||
public function getRegistrationSubscriptionRuleId(?int $storeId = null): int
|
||||
{
|
||||
return (int)$this->scopeConfig->getValue(
|
||||
self::XML_PATH_REGISTRATION_SUBSCRIPTION_RULE,
|
||||
ScopeInterface::SCOPE_STORE,
|
||||
$storeId
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Model\Config\Source;
|
||||
|
||||
use Magento\Framework\Data\OptionSourceInterface;
|
||||
use Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory;
|
||||
use Magento\SalesRule\Model\Rule;
|
||||
|
||||
class AutoGeneratedCartRule implements OptionSourceInterface
|
||||
{
|
||||
public function __construct(private readonly CollectionFactory $collectionFactory)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Return active cart rules that support generated coupon codes.
|
||||
*
|
||||
* @return array<int, array{value: int|string, label: \Stringable|string}>
|
||||
*/
|
||||
public function toOptionArray(): array
|
||||
{
|
||||
$collection = $this->collectionFactory->create();
|
||||
$collection->addFieldToSelect(['rule_id', 'name', 'coupon_type', 'use_auto_generation']);
|
||||
$collection->addFieldToFilter('is_active', 1);
|
||||
$collection->addFieldToFilter(
|
||||
['coupon_type', 'use_auto_generation'],
|
||||
[['eq' => Rule::COUPON_TYPE_AUTO], ['eq' => 1]]
|
||||
);
|
||||
$collection->setOrder('name', 'ASC');
|
||||
|
||||
$options = [['value' => '', 'label' => __('-- Disabled --')]];
|
||||
foreach ($collection as $rule) {
|
||||
$options[] = [
|
||||
'value' => (int)$rule->getId(),
|
||||
'label' => sprintf('%s (ID: %d)', (string)$rule->getName(), (int)$rule->getId()),
|
||||
];
|
||||
}
|
||||
|
||||
return $options;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Model\Coupon;
|
||||
|
||||
use Magento\SalesRule\Model\Rule;
|
||||
|
||||
class ConditionFormatter
|
||||
{
|
||||
/** @return string[] */
|
||||
public function format(Rule $rule): array
|
||||
{
|
||||
$description = trim(strip_tags((string)$rule->getDescription()));
|
||||
|
||||
return $description === '' ? [] : [$description];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Model\Coupon;
|
||||
|
||||
use Magento\Framework\Pricing\PriceCurrencyInterface;
|
||||
use Magento\SalesRule\Model\Rule;
|
||||
|
||||
class DiscountFormatter
|
||||
{
|
||||
public function __construct(private readonly PriceCurrencyInterface $priceCurrency)
|
||||
{
|
||||
}
|
||||
|
||||
public function format(Rule $rule): string
|
||||
{
|
||||
$amount = (float)$rule->getDiscountAmount();
|
||||
|
||||
return match ((string)$rule->getSimpleAction()) {
|
||||
Rule::BY_PERCENT_ACTION => (string)__('%1% OFF', $this->formatNumber($amount)),
|
||||
Rule::TO_PERCENT_ACTION => (string)__('Pay %1% of the item price', $this->formatNumber($amount)),
|
||||
Rule::BY_FIXED_ACTION => (string)__(
|
||||
'%1 OFF eligible items',
|
||||
$this->priceCurrency->convertAndFormat($amount, false)
|
||||
),
|
||||
Rule::TO_FIXED_ACTION => (string)__(
|
||||
'Eligible items for %1',
|
||||
$this->priceCurrency->convertAndFormat($amount, false)
|
||||
),
|
||||
Rule::CART_FIXED_ACTION => (string)__(
|
||||
'%1 OFF',
|
||||
$this->priceCurrency->convertAndFormat($amount, false)
|
||||
),
|
||||
Rule::BUY_X_GET_Y_ACTION => (string)__(
|
||||
'Buy %1, get %2 free',
|
||||
max(1, (int)$rule->getDiscountStep()),
|
||||
max(1, (int)$amount)
|
||||
),
|
||||
default => (string)__('Special offer'),
|
||||
};
|
||||
}
|
||||
|
||||
private function formatNumber(float $number): string
|
||||
{
|
||||
return rtrim(rtrim(number_format($number, 2, '.', ''), '0'), '.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Model\Coupon;
|
||||
|
||||
use Magento\Quote\Model\Quote;
|
||||
use Magento\SalesRule\Model\Rule;
|
||||
|
||||
class EligibilityService
|
||||
{
|
||||
public function isApplicableToQuote(Rule $rule, Quote $quote): bool
|
||||
{
|
||||
if (!$quote->getItemsCount()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$address = $quote->getIsVirtual() ? $quote->getBillingAddress() : $quote->getShippingAddress();
|
||||
if (!$rule->getConditions()->validate($address)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!$rule->getActions()->getConditions()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
foreach ($quote->getAllVisibleItems() as $item) {
|
||||
if ($rule->getActions()->validate($item)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Model\Coupon;
|
||||
|
||||
use Esun\CustomerCoupon\Model\ResourceModel\Assignment\CollectionFactory;
|
||||
use Magento\Quote\Model\Quote;
|
||||
use Magento\SalesRule\Model\ResourceModel\Rule\CollectionFactory as RuleCollectionFactory;
|
||||
use Magento\SalesRule\Model\Rule;
|
||||
|
||||
class ListProvider
|
||||
{
|
||||
public function __construct(
|
||||
private readonly CollectionFactory $assignmentCollectionFactory,
|
||||
private readonly RuleCollectionFactory $ruleCollectionFactory,
|
||||
private readonly StatusResolver $statusResolver,
|
||||
private readonly DiscountFormatter $discountFormatter,
|
||||
private readonly ConditionFormatter $conditionFormatter,
|
||||
private readonly EligibilityService $eligibilityService
|
||||
) {
|
||||
}
|
||||
|
||||
/** @return array<int,array<string,mixed>> */
|
||||
public function getForCustomer(
|
||||
int $customerId,
|
||||
int $websiteId,
|
||||
int $customerGroupId,
|
||||
?Quote $quote = null
|
||||
): array {
|
||||
$collection = $this->assignmentCollectionFactory->create();
|
||||
$collection->addFieldToFilter('main_table.customer_id', $customerId);
|
||||
$collection->getSelect()
|
||||
->joinInner(
|
||||
['coupon' => $collection->getTable('salesrule_coupon')],
|
||||
'main_table.coupon_id = coupon.coupon_id',
|
||||
[
|
||||
'code', 'usage_limit', 'usage_per_customer', 'times_used', 'expiration_date',
|
||||
]
|
||||
)
|
||||
->joinLeft(
|
||||
['coupon_usage' => $collection->getTable('salesrule_coupon_usage')],
|
||||
'coupon_usage.coupon_id = main_table.coupon_id'
|
||||
. ' AND coupon_usage.customer_id = main_table.customer_id',
|
||||
['customer_times_used' => 'times_used']
|
||||
)
|
||||
->order('main_table.assigned_at DESC');
|
||||
|
||||
$ruleIds = array_values(array_unique(array_map(
|
||||
'intval',
|
||||
$collection->getColumnValues('rule_id')
|
||||
)));
|
||||
if (!$ruleIds) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$rules = [];
|
||||
$ruleCollection = $this->ruleCollectionFactory->create()->addFieldToFilter('rule_id', ['in' => $ruleIds]);
|
||||
foreach ($ruleCollection as $rule) {
|
||||
$rules[(int)$rule->getId()] = $rule;
|
||||
}
|
||||
|
||||
$result = [];
|
||||
foreach ($collection as $assignment) {
|
||||
/** @var Rule|null $rule */
|
||||
$rule = $rules[(int)$assignment->getData('rule_id')] ?? null;
|
||||
if (!$rule) {
|
||||
continue;
|
||||
}
|
||||
$data = $assignment->getData();
|
||||
$data['customer_times_used'] = (int)($data['customer_times_used'] ?? 0);
|
||||
$status = $this->statusResolver->resolve($data, $rule, $websiteId, $customerGroupId);
|
||||
$cartApplicable = $status['status'] === 'available'
|
||||
&& ($quote === null || $this->eligibilityService->isApplicableToQuote($rule, $quote));
|
||||
$storeLabel = trim((string)$rule->getStoreLabel());
|
||||
|
||||
$result[] = [
|
||||
'assignment_id' => (int)$assignment->getId(),
|
||||
'code' => (string)$assignment->getData('code'),
|
||||
'rule_name' => $storeLabel,
|
||||
'discount_label' => $this->discountFormatter->format($rule),
|
||||
'conditions' => $this->conditionFormatter->format($rule),
|
||||
'expires_at' => $status['expires_at'],
|
||||
'status' => $status['status'],
|
||||
'status_reason' => $status['reason'],
|
||||
'cart_applicable' => $cartApplicable,
|
||||
];
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Model\Coupon;
|
||||
|
||||
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
|
||||
use Magento\SalesRule\Model\Rule;
|
||||
|
||||
class StatusResolver
|
||||
{
|
||||
public function __construct(private readonly TimezoneInterface $timezone)
|
||||
{
|
||||
}
|
||||
|
||||
/** @return array{status:string,reason:?string,expires_at:?string} */
|
||||
public function resolve(array $couponData, Rule $rule, int $websiteId, int $customerGroupId): array
|
||||
{
|
||||
$today = $this->timezone->date()->format('Y-m-d');
|
||||
$expiresAt = $this->getEffectiveExpiration($couponData, $rule);
|
||||
$reason = null;
|
||||
|
||||
if (!(bool)$rule->getIsActive()) {
|
||||
$reason = (string)__('Promotion is inactive');
|
||||
} elseif ($rule->getFromDate() && (string)$rule->getFromDate() > $today) {
|
||||
$reason = (string)__('Promotion has not started');
|
||||
} elseif ($expiresAt && $expiresAt < $today) {
|
||||
$reason = (string)__('Expired');
|
||||
} elseif (!in_array($websiteId, array_map('intval', $rule->getWebsiteIds()), true)) {
|
||||
$reason = (string)__('Not available on this website');
|
||||
} elseif (!in_array($customerGroupId, array_map('intval', $rule->getCustomerGroupIds()), true)) {
|
||||
$reason = (string)__('Not available for your customer group');
|
||||
} elseif ((int)$couponData['usage_limit'] > 0
|
||||
&& (int)$couponData['times_used'] >= (int)$couponData['usage_limit']) {
|
||||
$reason = (string)__('Usage limit reached');
|
||||
} elseif ((int)$couponData['usage_per_customer'] > 0
|
||||
&& (int)$couponData['customer_times_used'] >= (int)$couponData['usage_per_customer']) {
|
||||
$reason = (string)__('Used');
|
||||
}
|
||||
|
||||
return [
|
||||
'status' => $reason === null ? 'available' : 'unavailable',
|
||||
'reason' => $reason,
|
||||
'expires_at' => $expiresAt,
|
||||
];
|
||||
}
|
||||
|
||||
private function getEffectiveExpiration(array $couponData, Rule $rule): ?string
|
||||
{
|
||||
$dates = [];
|
||||
if ($rule->getToDate()) {
|
||||
$dates[] = substr((string)$rule->getToDate(), 0, 10);
|
||||
}
|
||||
if (!empty($couponData['expiration_date'])) {
|
||||
$dates[] = substr((string)$couponData['expiration_date'], 0, 10);
|
||||
}
|
||||
|
||||
return $dates ? min($dates) : null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Model\Notification;
|
||||
|
||||
use Esun\CustomerCoupon\Api\CouponNotifierInterface;
|
||||
|
||||
class NullCouponNotifier implements CouponNotifierInterface
|
||||
{
|
||||
public function notify(int $assignmentId): void
|
||||
{
|
||||
// Intentionally empty. A mail or webhook adapter can replace this implementation later.
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Model;
|
||||
|
||||
use Magento\Customer\Model\Session;
|
||||
|
||||
class RegistrationCouponGrantContext
|
||||
{
|
||||
private const SESSION_KEY = 'esun_registration_coupon_granted_customer_id';
|
||||
|
||||
public function __construct(private readonly Session $customerSession)
|
||||
{
|
||||
}
|
||||
|
||||
public function markGranted(int $customerId): void
|
||||
{
|
||||
if ($customerId > 0) {
|
||||
$this->customerSession->setData(self::SESSION_KEY, $customerId);
|
||||
}
|
||||
}
|
||||
|
||||
public function consumeGrantedCustomerId(): int
|
||||
{
|
||||
$customerId = (int)$this->customerSession->getData(self::SESSION_KEY);
|
||||
$this->customerSession->unsetData(self::SESSION_KEY);
|
||||
|
||||
return $customerId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Model;
|
||||
|
||||
use Esun\CustomerCoupon\Model\ResourceModel\Assignment as AssignmentResource;
|
||||
use Esun\PromotionPopup\Model\Config as PromotionConfig;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
|
||||
use Magento\SalesRule\Api\CouponManagementInterface;
|
||||
use Magento\SalesRule\Api\Data\CouponGenerationSpecInterface;
|
||||
use Magento\SalesRule\Api\Data\CouponGenerationSpecInterfaceFactory;
|
||||
use Magento\SalesRule\Model\Rule;
|
||||
use Magento\SalesRule\Model\RuleFactory;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class RegistrationSubscriptionCouponService
|
||||
{
|
||||
public const ASSIGNMENT_SOURCE = 'registration_newsletter';
|
||||
|
||||
public function __construct(
|
||||
private readonly Config $config,
|
||||
private readonly RuleFactory $ruleFactory,
|
||||
private readonly CouponGenerationSpecInterfaceFactory $generationSpecFactory,
|
||||
private readonly CouponManagementInterface $couponManagement,
|
||||
private readonly AssignmentService $assignmentService,
|
||||
private readonly AssignmentResource $assignmentResource,
|
||||
private readonly TimezoneInterface $timezone,
|
||||
private readonly StoreManagerInterface $storeManager,
|
||||
private readonly PromotionConfig $promotionConfig
|
||||
) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate and assign the one-time registration subscription coupon.
|
||||
*
|
||||
* @throws LocalizedException
|
||||
*/
|
||||
public function grant(int $customerId, int $websiteId, int $customerGroupId, int $storeId): bool
|
||||
{
|
||||
if ($customerId <= 0
|
||||
|| !$this->promotionConfig->isCampaignActive()
|
||||
|| !$this->promotionConfig->isRegistrationNewsletterCouponPromotion()
|
||||
|| $this->hasAlreadyBeenGranted($customerId)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$ruleId = $this->config->getRegistrationSubscriptionRuleId($storeId ?: null);
|
||||
if ($ruleId <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/** @var Rule $rule */
|
||||
$rule = $this->ruleFactory->create()->load($ruleId);
|
||||
$scope = $storeId > 0 ? $this->storeManager->getStore($storeId) : $this->storeManager->getStore();
|
||||
if (!$rule->getId()
|
||||
|| !$rule->getIsActive()
|
||||
|| ((int)$rule->getCouponType() !== Rule::COUPON_TYPE_AUTO && !$rule->getUseAutoGeneration())
|
||||
|| !in_array($websiteId, array_map('intval', $rule->getWebsiteIds()), true)
|
||||
|| !in_array($customerGroupId, array_map('intval', $rule->getCustomerGroupIds()), true)
|
||||
|| !$this->timezone->isScopeDateInInterval($scope, $rule->getFromDate(), $rule->getToDate())
|
||||
) {
|
||||
throw new LocalizedException(
|
||||
__('The configured registration subscription coupon rule is not eligible for this customer.')
|
||||
);
|
||||
}
|
||||
|
||||
/** @var CouponGenerationSpecInterface $specification */
|
||||
$specification = $this->generationSpecFactory->create();
|
||||
$specification->setRuleId($ruleId)
|
||||
->setQuantity(1)
|
||||
->setLength(12)
|
||||
->setFormat(CouponGenerationSpecInterface::COUPON_FORMAT_ALPHANUMERIC)
|
||||
->setPrefix('WELCOME-')
|
||||
->setDelimiterAtEvery(0);
|
||||
|
||||
$codes = $this->couponManagement->generate($specification);
|
||||
if (count($codes) !== 1) {
|
||||
if ($codes) {
|
||||
$this->couponManagement->deleteByCodes($codes);
|
||||
}
|
||||
throw new LocalizedException(__('The registration subscription coupon could not be generated.'));
|
||||
}
|
||||
|
||||
try {
|
||||
$this->assignmentService->assignCodes(
|
||||
$codes,
|
||||
[$customerId],
|
||||
$ruleId,
|
||||
self::ASSIGNMENT_SOURCE
|
||||
);
|
||||
} catch (\Throwable $exception) {
|
||||
$this->couponManagement->deleteByCodes($codes);
|
||||
if ($this->hasAlreadyBeenGranted($customerId)) {
|
||||
return true;
|
||||
}
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private function hasAlreadyBeenGranted(int $customerId): bool
|
||||
{
|
||||
$connection = $this->assignmentResource->getConnection();
|
||||
$select = $connection->select()
|
||||
->from($this->assignmentResource->getMainTable(), ['entity_id'])
|
||||
->where('customer_id = ?', $customerId)
|
||||
->where('source = ?', self::ASSIGNMENT_SOURCE)
|
||||
->limit(1);
|
||||
|
||||
return (bool)$connection->fetchOne($select);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Model\ResourceModel;
|
||||
|
||||
use Magento\Framework\Model\ResourceModel\Db\AbstractDb;
|
||||
|
||||
class Assignment extends AbstractDb
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init('esun_customer_coupon', 'entity_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Model\ResourceModel\Assignment;
|
||||
|
||||
use Esun\CustomerCoupon\Model\Assignment as AssignmentModel;
|
||||
use Esun\CustomerCoupon\Model\ResourceModel\Assignment as AssignmentResource;
|
||||
use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection;
|
||||
|
||||
class Collection extends AbstractCollection
|
||||
{
|
||||
protected function _construct(): void
|
||||
{
|
||||
$this->_init(AssignmentModel::class, AssignmentResource::class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Observer;
|
||||
|
||||
use Esun\CustomerCoupon\Block\Adminhtml\Form\CustomerSelect;
|
||||
use Magento\Framework\Event\Observer;
|
||||
use Magento\Framework\Event\ObserverInterface;
|
||||
use Magento\Framework\View\LayoutInterface;
|
||||
|
||||
class AddCustomerSelectToCouponForm implements ObserverInterface
|
||||
{
|
||||
public function __construct(private readonly LayoutInterface $layout)
|
||||
{
|
||||
}
|
||||
|
||||
public function execute(Observer $observer): void
|
||||
{
|
||||
$form = $observer->getData('form');
|
||||
$fieldset = $form ? $form->getElement('information_fieldset') : null;
|
||||
if (!$fieldset || $form->getElement('customer_ids')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$html = $this->layout->createBlock(CustomerSelect::class)
|
||||
->setTemplate('Esun_CustomerCoupon::form/customer-select.phtml')
|
||||
->toHtml();
|
||||
|
||||
$fieldset->addField(
|
||||
'customer_ids',
|
||||
'note',
|
||||
[
|
||||
'label' => __('Assigned Customers'),
|
||||
'text' => $html,
|
||||
'note' => __('When customers are selected, one unique coupon is generated for each customer.'),
|
||||
],
|
||||
'dash'
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Observer;
|
||||
|
||||
use Esun\CustomerCoupon\Model\RegistrationSubscriptionCouponService;
|
||||
use Esun\CustomerCoupon\Model\RegistrationCouponGrantContext;
|
||||
use Magento\Framework\Event\Observer;
|
||||
use Magento\Framework\Event\ObserverInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class GrantRegistrationSubscriptionCoupon implements ObserverInterface
|
||||
{
|
||||
public function __construct(
|
||||
private readonly RegistrationSubscriptionCouponService $couponService,
|
||||
private readonly RegistrationCouponGrantContext $grantContext,
|
||||
private readonly LoggerInterface $logger
|
||||
) {
|
||||
}
|
||||
|
||||
public function execute(Observer $observer): void
|
||||
{
|
||||
$controller = $observer->getEvent()->getAccountController();
|
||||
$subscriptionRequested = $controller?->getRequest()->getParam('is_subscribed', false);
|
||||
if (!in_array(strtolower((string)$subscriptionRequested), ['1', 'true', 'yes', 'on'], true)) {
|
||||
return;
|
||||
}
|
||||
|
||||
$customer = $observer->getEvent()->getCustomer();
|
||||
$customerId = (int)($customer?->getId() ?? 0);
|
||||
if ($customerId <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
$granted = $this->couponService->grant(
|
||||
$customerId,
|
||||
(int)$customer->getWebsiteId(),
|
||||
(int)$customer->getGroupId(),
|
||||
(int)$customer->getStoreId()
|
||||
);
|
||||
if ($granted) {
|
||||
$this->grantContext->markGranted($customerId);
|
||||
}
|
||||
} catch (\Throwable $exception) {
|
||||
// Coupon delivery must never roll back an otherwise successful customer registration.
|
||||
$this->logger->error('Unable to grant registration subscription coupon.', [
|
||||
'customer_id' => $customerId,
|
||||
'exception' => $exception,
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Plugin;
|
||||
|
||||
use Esun\CustomerCoupon\Model\AssignmentService;
|
||||
use Magento\Customer\Model\ResourceModel\Customer\CollectionFactory as CustomerCollectionFactory;
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
use Magento\Framework\Escaper;
|
||||
use Magento\Framework\Exception\LocalizedException;
|
||||
use Magento\Framework\Json\Helper\Data as JsonHelper;
|
||||
use Magento\SalesRule\Api\CouponManagementInterface;
|
||||
use Magento\SalesRule\Api\Data\CouponGenerationSpecInterfaceFactory;
|
||||
use Magento\SalesRule\Controller\Adminhtml\Promo\Quote\Generate;
|
||||
use Magento\SalesRule\Model\Quote\GetCouponCodeLengthInterface;
|
||||
use Magento\SalesRule\Model\Rule;
|
||||
use Magento\SalesRule\Model\RuleFactory;
|
||||
use Magento\Store\Model\ScopeInterface;
|
||||
use Psr\Log\LoggerInterface;
|
||||
|
||||
class GenerateAssignedCouponsPlugin
|
||||
{
|
||||
private const XML_CONFIG_COUPON_QUANTITY_LIMIT = 'promo/auto_generated_coupon_codes/quantity_limit';
|
||||
|
||||
public function __construct(
|
||||
private readonly CouponGenerationSpecInterfaceFactory $generationSpecFactory,
|
||||
private readonly CouponManagementInterface $couponManagement,
|
||||
private readonly AssignmentService $assignmentService,
|
||||
private readonly RuleFactory $ruleFactory,
|
||||
private readonly CustomerCollectionFactory $customerCollectionFactory,
|
||||
private readonly GetCouponCodeLengthInterface $getCouponCodeLength,
|
||||
private readonly ScopeConfigInterface $scopeConfig,
|
||||
private readonly JsonHelper $jsonHelper,
|
||||
private readonly Escaper $escaper,
|
||||
private readonly LoggerInterface $logger
|
||||
) {
|
||||
}
|
||||
|
||||
public function aroundExecute(Generate $subject, callable $proceed): mixed
|
||||
{
|
||||
$customerIds = $this->parseCustomerIds($subject->getRequest()->getParam('customer_ids'));
|
||||
if (!$customerIds) {
|
||||
return $proceed();
|
||||
}
|
||||
|
||||
try {
|
||||
$data = $subject->getRequest()->getParams();
|
||||
$ruleId = (int)($data['rule_id'] ?? 0);
|
||||
$rule = $this->ruleFactory->create()->load($ruleId);
|
||||
if (!$rule->getId()) {
|
||||
throw new LocalizedException(__('Rule is not defined.'));
|
||||
}
|
||||
if ((int)$rule->getCouponType() !== Rule::COUPON_TYPE_AUTO && !$rule->getUseAutoGeneration()) {
|
||||
throw new LocalizedException(
|
||||
__('The rule coupon settings changed. Please save the rule before using auto-generation.')
|
||||
);
|
||||
}
|
||||
|
||||
$this->validateCustomers($customerIds, $rule);
|
||||
$quantityLimit = (int)$this->scopeConfig->getValue(
|
||||
self::XML_CONFIG_COUPON_QUANTITY_LIMIT,
|
||||
ScopeInterface::SCOPE_STORE
|
||||
);
|
||||
if ($quantityLimit > 0 && count($customerIds) > $quantityLimit) {
|
||||
throw new LocalizedException(__('The selected customer count exceeds the configured coupon limit.'));
|
||||
}
|
||||
|
||||
$data['qty'] = count($customerIds);
|
||||
$data['quantity'] = count($customerIds);
|
||||
if ((int)($data['length'] ?? 0) !== $this->getCouponCodeLength->fetchCouponCodeLength($data)) {
|
||||
throw new LocalizedException(
|
||||
__('The coupon code length is too short for the selected customer count.')
|
||||
);
|
||||
}
|
||||
|
||||
$specification = $this->generationSpecFactory->create(['data' => $data]);
|
||||
$codes = $this->couponManagement->generate($specification);
|
||||
try {
|
||||
$this->assignmentService->assignCodes($codes, $customerIds, $ruleId);
|
||||
} catch (\Throwable $exception) {
|
||||
$this->couponManagement->deleteByCodes($codes);
|
||||
throw $exception;
|
||||
}
|
||||
|
||||
return $this->respond($subject, [
|
||||
'messages' => '<div class="messages"><div class="message message-success success"><div>'
|
||||
. $this->escaper->escapeHtml(
|
||||
__('Generated and assigned %1 coupon(s).', count($customerIds))
|
||||
)
|
||||
. '</div></div></div>',
|
||||
]);
|
||||
} catch (LocalizedException $exception) {
|
||||
return $this->respond($subject, ['error' => $exception->getMessage()]);
|
||||
} catch (\Throwable $exception) {
|
||||
$this->logger->critical($exception);
|
||||
|
||||
return $this->respond($subject, [
|
||||
'error' => (string)__('Something went wrong while generating assigned coupons.'),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
/** @return int[] */
|
||||
private function parseCustomerIds(mixed $value): array
|
||||
{
|
||||
$values = is_array($value) ? $value : explode(',', (string)$value);
|
||||
$ids = array_values(array_unique(array_filter(array_map('intval', $values))));
|
||||
|
||||
return $ids;
|
||||
}
|
||||
|
||||
/** @param int[] $customerIds */
|
||||
private function validateCustomers(array $customerIds, Rule $rule): void
|
||||
{
|
||||
$collection = $this->customerCollectionFactory->create();
|
||||
$collection->addFieldToFilter('entity_id', ['in' => $customerIds]);
|
||||
$collection->addFieldToFilter('website_id', ['in' => array_map('intval', $rule->getWebsiteIds())]);
|
||||
$collection->addFieldToFilter('group_id', ['in' => array_map('intval', $rule->getCustomerGroupIds())]);
|
||||
|
||||
if ((int)$collection->getSize() !== count($customerIds)) {
|
||||
throw new LocalizedException(
|
||||
__('One or more selected customers are not eligible for this rule website or customer group.')
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function respond(Generate $subject, array $data): mixed
|
||||
{
|
||||
return $subject->getResponse()->representJson($this->jsonHelper->jsonEncode($data));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Plugin;
|
||||
|
||||
use Esun\CustomerCoupon\Model\RegistrationCouponGrantContext;
|
||||
use Magento\Customer\Controller\Account\CreatePost;
|
||||
use Magento\Customer\Model\Session;
|
||||
use Magento\Framework\Controller\Result\Redirect as ResultRedirect;
|
||||
use Magento\Framework\Message\ManagerInterface;
|
||||
use Magento\Framework\UrlInterface;
|
||||
|
||||
class RedirectAfterRegistrationCouponGrant
|
||||
{
|
||||
public function __construct(
|
||||
private readonly RegistrationCouponGrantContext $grantContext,
|
||||
private readonly Session $customerSession,
|
||||
private readonly ManagerInterface $messageManager,
|
||||
private readonly UrlInterface $urlBuilder
|
||||
) {
|
||||
}
|
||||
|
||||
public function afterExecute(CreatePost $subject, mixed $result): mixed
|
||||
{
|
||||
$grantedCustomerId = $this->grantContext->consumeGrantedCustomerId();
|
||||
if ($grantedCustomerId <= 0
|
||||
|| !$result instanceof ResultRedirect
|
||||
|| !$this->customerSession->isLoggedIn()
|
||||
|| (int)$this->customerSession->getCustomerId() !== $grantedCustomerId
|
||||
) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$this->messageManager->addSuccessMessage(
|
||||
__('Your registration coupon has been added to My Coupons.')
|
||||
);
|
||||
$result->setUrl($this->urlBuilder->getUrl(
|
||||
'customer-coupon/account/index',
|
||||
['_secure' => true]
|
||||
));
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\Plugin;
|
||||
|
||||
use Magento\Framework\App\ResourceConnection;
|
||||
use Magento\SalesRule\Model\ValidateCouponCode;
|
||||
|
||||
class ValidateAssignedCouponPlugin
|
||||
{
|
||||
public function __construct(private readonly ResourceConnection $resourceConnection)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* @param string[] $result
|
||||
* @param string[] $couponCodes
|
||||
* @return string[]
|
||||
*/
|
||||
public function afterExecute(
|
||||
ValidateCouponCode $subject,
|
||||
array $result,
|
||||
array $couponCodes,
|
||||
?int $customerId = null
|
||||
): array {
|
||||
if (!$result) {
|
||||
return $result;
|
||||
}
|
||||
|
||||
$connection = $this->resourceConnection->getConnection();
|
||||
$select = $connection->select()
|
||||
->from(['coupon' => $this->resourceConnection->getTableName('salesrule_coupon')], ['code'])
|
||||
->joinInner(
|
||||
['assignment' => $this->resourceConnection->getTableName('esun_customer_coupon')],
|
||||
'assignment.coupon_id = coupon.coupon_id',
|
||||
['customer_id']
|
||||
)
|
||||
->where('coupon.code IN (?)', array_values($result));
|
||||
$assigned = $connection->fetchPairs($select);
|
||||
|
||||
foreach ($result as $ruleId => $code) {
|
||||
if (isset($assigned[$code]) && (!$customerId || (int)$assigned[$code] !== $customerId)) {
|
||||
unset($result[$ruleId]);
|
||||
}
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
# Customer Coupons
|
||||
|
||||
如果给用户的优惠券有限制条件,请在 rule 的 Description 中填写。
|
||||
|
||||
## 注册并订阅赠券
|
||||
|
||||
1. 创建或编辑一个 Cart Price Rule:使用自动生成优惠码,并在规则中设置满 $299、减 $24、每张券使用一次,以及允许与其他规则叠加。
|
||||
2. 在 `Stores > Configuration > Esun > Customer Coupons` 选择该规则。
|
||||
3. 新用户在网站注册时勾选 Newsletter 订阅后,系统自动生成一张以 `WELCOME-` 开头的券并加入 `My Coupons`。
|
||||
|
||||
每位客户只会获得一次此来源的赠券;后台手动分配的其他优惠券不受影响。清空规则配置即可停止活动。
|
||||
@@ -0,0 +1,95 @@
|
||||
<?php
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Esun\CustomerCoupon\ViewModel;
|
||||
|
||||
use Esun\CustomerCoupon\Model\Config as CouponConfig;
|
||||
use Esun\CustomerCoupon\Model\Coupon\DiscountFormatter;
|
||||
use Esun\PromotionPopup\Model\Config as PromotionConfig;
|
||||
use Magento\Framework\App\Config\ScopeConfigInterface;
|
||||
use Magento\Framework\Stdlib\DateTime\TimezoneInterface;
|
||||
use Magento\Framework\View\Element\Block\ArgumentInterface;
|
||||
use Magento\SalesRule\Model\Rule;
|
||||
use Magento\SalesRule\Model\RuleFactory;
|
||||
use Magento\Store\Model\ScopeInterface;
|
||||
use Magento\Store\Model\StoreManagerInterface;
|
||||
|
||||
class RegistrationSubscriptionPromotion implements ArgumentInterface
|
||||
{
|
||||
private const XML_PATH_DEFAULT_CUSTOMER_GROUP = 'customer/create_account/default_group';
|
||||
|
||||
private bool $ruleResolved = false;
|
||||
private ?Rule $eligibleRule = null;
|
||||
|
||||
public function __construct(
|
||||
private readonly CouponConfig $couponConfig,
|
||||
private readonly PromotionConfig $promotionConfig,
|
||||
private readonly RuleFactory $ruleFactory,
|
||||
private readonly StoreManagerInterface $storeManager,
|
||||
private readonly TimezoneInterface $timezone,
|
||||
private readonly ScopeConfigInterface $scopeConfig,
|
||||
private readonly DiscountFormatter $discountFormatter
|
||||
) {
|
||||
}
|
||||
|
||||
public function isReminderEnabled(): bool
|
||||
{
|
||||
return $this->getEligibleRule() !== null;
|
||||
}
|
||||
|
||||
public function getReminderMessage(): string
|
||||
{
|
||||
$rule = $this->getEligibleRule();
|
||||
|
||||
return $rule
|
||||
? (string)__('Subscribe now to receive your %1 coupon.', $this->discountFormatter->format($rule))
|
||||
: '';
|
||||
}
|
||||
|
||||
public function getDiscountLabel(): string
|
||||
{
|
||||
$rule = $this->getEligibleRule();
|
||||
|
||||
return $rule ? $this->discountFormatter->format($rule) : '';
|
||||
}
|
||||
|
||||
private function getEligibleRule(): ?Rule
|
||||
{
|
||||
if ($this->ruleResolved) {
|
||||
return $this->eligibleRule;
|
||||
}
|
||||
$this->ruleResolved = true;
|
||||
|
||||
if (!$this->promotionConfig->isCampaignActive()
|
||||
|| !$this->promotionConfig->isRegistrationNewsletterCouponPromotion()
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$store = $this->storeManager->getStore();
|
||||
$ruleId = $this->couponConfig->getRegistrationSubscriptionRuleId((int)$store->getId());
|
||||
if ($ruleId <= 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @var Rule $rule */
|
||||
$rule = $this->ruleFactory->create()->load($ruleId);
|
||||
$websiteId = (int)$store->getWebsiteId();
|
||||
$defaultGroupId = (int)$this->scopeConfig->getValue(
|
||||
self::XML_PATH_DEFAULT_CUSTOMER_GROUP,
|
||||
ScopeInterface::SCOPE_STORE,
|
||||
(int)$store->getId()
|
||||
);
|
||||
|
||||
$eligible = (bool)$rule->getId()
|
||||
&& (bool)$rule->getIsActive()
|
||||
&& ((int)$rule->getCouponType() === Rule::COUPON_TYPE_AUTO || (bool)$rule->getUseAutoGeneration())
|
||||
&& in_array($websiteId, array_map('intval', $rule->getWebsiteIds()), true)
|
||||
&& in_array($defaultGroupId, array_map('intval', $rule->getCustomerGroupIds()), true)
|
||||
&& $this->timezone->isScopeDateInInterval($store, $rule->getFromDate(), $rule->getToDate());
|
||||
|
||||
$this->eligibleRule = $eligible ? $rule : null;
|
||||
|
||||
return $this->eligibleRule;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
<?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_Backend::stores">
|
||||
<resource id="Magento_Backend::stores_settings">
|
||||
<resource id="Magento_Config::config">
|
||||
<resource id="Esun_CustomerCoupon::configuration"
|
||||
title="Customer Coupon Configuration" sortOrder="90"/>
|
||||
</resource>
|
||||
</resource>
|
||||
</resource>
|
||||
</resource>
|
||||
</resources>
|
||||
</acl>
|
||||
</config>
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
|
||||
<preference for="Magento\SalesRule\Block\Adminhtml\Promo\Quote\Edit\Tab\Coupons\Grid"
|
||||
type="Esun\CustomerCoupon\Block\Adminhtml\Promo\Quote\Edit\Tab\Coupons\Grid"/>
|
||||
<type name="Magento\SalesRule\Controller\Adminhtml\Promo\Quote\Generate">
|
||||
<plugin name="esun_customer_coupon_generate_for_customers"
|
||||
type="Esun\CustomerCoupon\Plugin\GenerateAssignedCouponsPlugin" sortOrder="10"/>
|
||||
</type>
|
||||
</config>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?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="adminhtml_promo_quote_edit_tab_coupons_form_prepare_form">
|
||||
<observer name="esun_customer_coupon_add_customer_select"
|
||||
instance="Esun\CustomerCoupon\Observer\AddCustomerSelectToCouponForm"/>
|
||||
</event>
|
||||
</config>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?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_customer_coupon" frontName="esun_customer_coupon">
|
||||
<module name="Esun_CustomerCoupon" before="Magento_Backend"/>
|
||||
</route>
|
||||
</router>
|
||||
</config>
|
||||
@@ -0,0 +1,25 @@
|
||||
<?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>
|
||||
<tab id="esun" translate="label" sortOrder="300">
|
||||
<label>Esun</label>
|
||||
</tab>
|
||||
<section id="esun_customer_coupon" translate="label" type="text" sortOrder="360"
|
||||
showInDefault="1" showInWebsite="1" showInStore="0">
|
||||
<label>Customer Coupons</label>
|
||||
<tab>esun</tab>
|
||||
<resource>Esun_CustomerCoupon::configuration</resource>
|
||||
<group id="registration_subscription" translate="label" type="text" sortOrder="10"
|
||||
showInDefault="1" showInWebsite="1" showInStore="0">
|
||||
<label>Registration Subscription Coupon</label>
|
||||
<field id="rule_id" translate="label comment" type="select" sortOrder="10"
|
||||
showInDefault="1" showInWebsite="1" showInStore="0">
|
||||
<label>Cart Price Rule</label>
|
||||
<comment>Selecting a rule enables the reward. Only active rules that allow auto-generated coupons are listed. Configure the $299 minimum, $24 fixed discount, usage limits and stacking behavior on the Cart Price Rule itself.</comment>
|
||||
<source_model>Esun\CustomerCoupon\Model\Config\Source\AutoGeneratedCartRule</source_model>
|
||||
</field>
|
||||
</group>
|
||||
</section>
|
||||
</system>
|
||||
</config>
|
||||
@@ -0,0 +1,48 @@
|
||||
<?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_customer_coupon" resource="default" engine="innodb"
|
||||
comment="Customer Assigned Coupon">
|
||||
<column xsi:type="int" name="entity_id" unsigned="true" nullable="false" identity="true"
|
||||
comment="Entity ID"/>
|
||||
<column xsi:type="int" name="coupon_id" unsigned="true" nullable="false"
|
||||
comment="Coupon ID"/>
|
||||
<column xsi:type="int" name="rule_id" unsigned="true" nullable="false"
|
||||
comment="Sales Rule ID"/>
|
||||
<column xsi:type="int" name="customer_id" unsigned="true" nullable="false"
|
||||
comment="Customer ID"/>
|
||||
<column xsi:type="varchar" name="source" nullable="true" length="64"
|
||||
comment="Assignment Source"/>
|
||||
<column xsi:type="timestamp" name="assigned_at" nullable="false" default="CURRENT_TIMESTAMP"
|
||||
on_update="false" comment="Assigned At"/>
|
||||
<column xsi:type="timestamp" name="created_at" nullable="false" default="CURRENT_TIMESTAMP"
|
||||
on_update="false" comment="Created At"/>
|
||||
|
||||
<constraint xsi:type="primary" referenceId="PRIMARY">
|
||||
<column name="entity_id"/>
|
||||
</constraint>
|
||||
<constraint xsi:type="unique" referenceId="ESUN_CUSTOMER_COUPON_COUPON_ID_UNQ">
|
||||
<column name="coupon_id"/>
|
||||
</constraint>
|
||||
<constraint xsi:type="unique" referenceId="ESUN_CUSTOMER_COUPON_CUSTOMER_ID_SOURCE_UNQ">
|
||||
<column name="customer_id"/>
|
||||
<column name="source"/>
|
||||
</constraint>
|
||||
<constraint xsi:type="foreign" referenceId="ESUN_CUSTOMER_COUPON_COUPON_ID_SALESRULE_COUPON_COUPON_ID"
|
||||
table="esun_customer_coupon" column="coupon_id"
|
||||
referenceTable="salesrule_coupon" referenceColumn="coupon_id" onDelete="CASCADE"/>
|
||||
<constraint xsi:type="foreign" referenceId="ESUN_CUSTOMER_COUPON_RULE_ID_SALESRULE_RULE_ID"
|
||||
table="esun_customer_coupon" column="rule_id"
|
||||
referenceTable="salesrule" referenceColumn="rule_id" onDelete="CASCADE"/>
|
||||
<constraint xsi:type="foreign" referenceId="ESUN_CUSTOMER_COUPON_CUSTOMER_ID_CUSTOMER_ENTITY_ENTITY_ID"
|
||||
table="esun_customer_coupon" column="customer_id"
|
||||
referenceTable="customer_entity" referenceColumn="entity_id" onDelete="CASCADE"/>
|
||||
<index referenceId="ESUN_CUSTOMER_COUPON_CUSTOMER_ID_COUPON_ID" indexType="btree">
|
||||
<column name="customer_id"/>
|
||||
<column name="coupon_id"/>
|
||||
</index>
|
||||
<index referenceId="ESUN_CUSTOMER_COUPON_RULE_ID" indexType="btree">
|
||||
<column name="rule_id"/>
|
||||
</index>
|
||||
</table>
|
||||
</schema>
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"esun_customer_coupon": {
|
||||
"column": {
|
||||
"entity_id": true,
|
||||
"coupon_id": true,
|
||||
"rule_id": true,
|
||||
"customer_id": true,
|
||||
"source": true,
|
||||
"assigned_at": true,
|
||||
"created_at": true
|
||||
},
|
||||
"constraint": {
|
||||
"PRIMARY": true,
|
||||
"ESUN_CUSTOMER_COUPON_COUPON_ID_UNQ": true,
|
||||
"ESUN_CUSTOMER_COUPON_CUSTOMER_ID_SOURCE_UNQ": true,
|
||||
"ESUN_CUSTOMER_COUPON_COUPON_ID_SALESRULE_COUPON_COUPON_ID": true,
|
||||
"ESUN_CUSTOMER_COUPON_RULE_ID_SALESRULE_RULE_ID": true,
|
||||
"ESUN_CUSTOMER_COUPON_CUSTOMER_ID_CUSTOMER_ENTITY_ENTITY_ID": true,
|
||||
"ESUN_CUSTOMER_COUPON_COUPON_ID": true,
|
||||
"ESUN_CUSTOMER_COUPON_CUSTOMER_ID_SOURCE": true
|
||||
},
|
||||
"index": {
|
||||
"ESUN_CUSTOMER_COUPON_CUSTOMER_ID_COUPON_ID": true,
|
||||
"ESUN_CUSTOMER_COUPON_RULE_ID": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
<?xml version="1.0"?>
|
||||
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
|
||||
<preference for="Esun\CustomerCoupon\Api\CouponNotifierInterface"
|
||||
type="Esun\CustomerCoupon\Model\Notification\NullCouponNotifier"/>
|
||||
<type name="Magento\SalesRule\Model\ValidateCouponCode">
|
||||
<plugin name="esun_customer_coupon_validate_assignee"
|
||||
type="Esun\CustomerCoupon\Plugin\ValidateAssignedCouponPlugin" sortOrder="20"/>
|
||||
</type>
|
||||
</config>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?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\Customer\Controller\Account\CreatePost">
|
||||
<plugin name="esun_redirect_after_registration_coupon_grant"
|
||||
type="Esun\CustomerCoupon\Plugin\RedirectAfterRegistrationCouponGrant"
|
||||
sortOrder="20"/>
|
||||
</type>
|
||||
</config>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?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_customer_coupon_registration_subscription"
|
||||
instance="Esun\CustomerCoupon\Observer\GrantRegistrationSubscriptionCoupon"/>
|
||||
</event>
|
||||
</config>
|
||||
@@ -0,0 +1,9 @@
|
||||
<?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="customer_coupon" frontName="customer-coupon">
|
||||
<module name="Esun_CustomerCoupon"/>
|
||||
</route>
|
||||
</router>
|
||||
</config>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?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_CustomerCoupon">
|
||||
<sequence>
|
||||
<module name="Magento_SalesRule"/>
|
||||
<module name="Magento_Customer"/>
|
||||
<module name="Magento_Newsletter"/>
|
||||
<module name="Magento_Checkout"/>
|
||||
<module name="Esun_Cart"/>
|
||||
<module name="Esun_PromotionPopup"/>
|
||||
</sequence>
|
||||
</module>
|
||||
</config>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?php
|
||||
use Magento\Framework\Component\ComponentRegistrar;
|
||||
|
||||
ComponentRegistrar::register(
|
||||
ComponentRegistrar::MODULE,
|
||||
'Esun_CustomerCoupon',
|
||||
__DIR__
|
||||
);
|
||||
@@ -0,0 +1,7 @@
|
||||
<?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_CustomerCoupon::css/customer-select.css"/>
|
||||
</head>
|
||||
</page>
|
||||
@@ -0,0 +1,5 @@
|
||||
var config = {
|
||||
deps: [
|
||||
'Esun_CustomerCoupon/js/form/customer-select-bootstrap'
|
||||
]
|
||||
};
|
||||
@@ -0,0 +1,40 @@
|
||||
<?php
|
||||
/** @var \Esun\CustomerCoupon\Block\Adminhtml\Form\CustomerSelect $block */
|
||||
/** @var \Magento\Framework\Escaper $escaper */
|
||||
?>
|
||||
<div class="esun-customer-coupon-select">
|
||||
<div data-role="esun-customer-coupon-scope" data-bind="scope: 'esunCustomerCouponSelect'">
|
||||
<input type="hidden" name="customer_ids" data-bind="value: value"/>
|
||||
<!-- ko template: getTemplate() --><!-- /ko -->
|
||||
</div>
|
||||
</div>
|
||||
<script type="text/x-magento-init">
|
||||
{
|
||||
".esun-customer-coupon-select": {
|
||||
"Magento_Ui/js/core/app": {
|
||||
"components": {
|
||||
"esunCustomerCouponSelect": {
|
||||
"component": "Esun_CustomerCoupon/js/form/element/customer-select",
|
||||
"dataScope": "customer_ids",
|
||||
"template": "ui/grid/filters/elements/ui-select",
|
||||
"disableLabel": true,
|
||||
"multiple": true,
|
||||
"showCheckbox": true,
|
||||
"showPath": false,
|
||||
"chipsEnabled": true,
|
||||
"filterOptions": true,
|
||||
"searchOptions": true,
|
||||
"searchUrl": "<?= $escaper->escapeJs($escaper->escapeUrl($block->getSearchUrl())) ?>",
|
||||
"filterPlaceholder": "<?= $escaper->escapeJs(__('Search by name, email, or customer ID')) ?>",
|
||||
"selectedPlaceholders": {
|
||||
"defaultPlaceholder": "<?= $escaper->escapeJs(__('Search and select customers')) ?>",
|
||||
"lotPlaceholders": "<?= $escaper->escapeJs(__('customers selected')) ?>"
|
||||
},
|
||||
"pageLimit": 20,
|
||||
"options": []
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,9 @@
|
||||
.admin__scope-old #coupons_customer_ids.control-value {
|
||||
display: block;
|
||||
padding-top: 0;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.esun-customer-coupon-select {
|
||||
width: 100%;
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
define([
|
||||
'ko',
|
||||
'mage/apply/main',
|
||||
'Magento_Ui/js/lib/knockout/bootstrap'
|
||||
], function (ko, mage) {
|
||||
'use strict';
|
||||
|
||||
var selector = '.esun-customer-coupon-select',
|
||||
initializedAttribute = 'data-esun-customer-coupon-initialized';
|
||||
|
||||
function initialize(element) {
|
||||
var scope;
|
||||
|
||||
if (element.hasAttribute(initializedAttribute)) {
|
||||
return;
|
||||
}
|
||||
|
||||
element.setAttribute(initializedAttribute, 'true');
|
||||
|
||||
// The coupons form is inserted through Magento_Ui's `html` binding after
|
||||
// the normal x-magento-init and Knockout bootstrap passes have completed.
|
||||
mage.apply(element);
|
||||
|
||||
scope = element.querySelector('[data-role="esun-customer-coupon-scope"]');
|
||||
if (scope) {
|
||||
ko.applyBindings({}, scope);
|
||||
}
|
||||
}
|
||||
|
||||
function scan(context) {
|
||||
var elements = [];
|
||||
|
||||
if (context.nodeType !== 1 && context.nodeType !== 9) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (context.nodeType === 1 && context.matches(selector)) {
|
||||
elements.push(context);
|
||||
}
|
||||
|
||||
Array.prototype.push.apply(elements, context.querySelectorAll(selector));
|
||||
elements.forEach(initialize);
|
||||
}
|
||||
|
||||
function start() {
|
||||
scan(document);
|
||||
|
||||
new MutationObserver(function (mutations) {
|
||||
mutations.forEach(function (mutation) {
|
||||
Array.prototype.forEach.call(mutation.addedNodes, scan);
|
||||
});
|
||||
}).observe(document.body, {childList: true, subtree: true});
|
||||
}
|
||||
|
||||
if (document.readyState === 'loading') {
|
||||
document.addEventListener('DOMContentLoaded', start);
|
||||
} else {
|
||||
start();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,101 @@
|
||||
define([
|
||||
'Magento_Ui/js/form/element/ui-select'
|
||||
], function (UiSelect) {
|
||||
'use strict';
|
||||
|
||||
return UiSelect.extend({
|
||||
defaults: {
|
||||
// This component is mounted in a legacy form rather than under a UI form provider.
|
||||
dataScope: 'customer_ids',
|
||||
showPath: false
|
||||
},
|
||||
|
||||
initialize: function () {
|
||||
this.selectedOptionsByValue = {};
|
||||
this._super();
|
||||
this.value.subscribe(this.syncQuantity, this);
|
||||
this.syncQuantity(this.value());
|
||||
|
||||
return this;
|
||||
},
|
||||
|
||||
/**
|
||||
* Keep the complete option objects independently from the current AJAX
|
||||
* result set. Magento replaces cacheOptions.plain for every new search.
|
||||
*/
|
||||
toggleOptionSelected: function (option) {
|
||||
var key = String(option.value);
|
||||
|
||||
if (this.isSelected(option.value)) {
|
||||
delete this.selectedOptionsByValue[key];
|
||||
} else {
|
||||
this.selectedOptionsByValue[key] = option;
|
||||
}
|
||||
|
||||
return this._super(option);
|
||||
},
|
||||
|
||||
removeSelected: function (value, data, event) {
|
||||
delete this.selectedOptionsByValue[String(value)];
|
||||
|
||||
return this._super(value, data, event);
|
||||
},
|
||||
|
||||
getSelected: function () {
|
||||
var values = this.value(),
|
||||
availableOptions = this.cacheOptions && this.cacheOptions.plain || [],
|
||||
selectedOptions = [],
|
||||
optionsByValue = this.selectedOptionsByValue || {};
|
||||
|
||||
values = Array.isArray(values) ? values : values ? [values] : [];
|
||||
|
||||
values.forEach(function (value) {
|
||||
var key = String(value),
|
||||
option = optionsByValue[key];
|
||||
|
||||
if (!option) {
|
||||
availableOptions.some(function (candidate) {
|
||||
if (String(candidate.value) === key) {
|
||||
option = candidate;
|
||||
optionsByValue[key] = candidate;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
if (option) {
|
||||
selectedOptions.push(option);
|
||||
}
|
||||
});
|
||||
|
||||
return selectedOptions;
|
||||
},
|
||||
|
||||
syncQuantity: function (value) {
|
||||
var quantity = Array.isArray(value) ? value.length : 0,
|
||||
input = document.getElementById('coupons_qty');
|
||||
|
||||
if (!input) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (quantity > 0) {
|
||||
if (!input.hasAttribute('data-esun-original-qty')) {
|
||||
input.setAttribute('data-esun-original-qty', input.value || '');
|
||||
}
|
||||
input.value = quantity;
|
||||
input.readOnly = true;
|
||||
input.dispatchEvent(new Event('change', {bubbles: true}));
|
||||
} else {
|
||||
input.readOnly = false;
|
||||
if (input.hasAttribute('data-esun-original-qty')) {
|
||||
input.value = input.getAttribute('data-esun-original-qty');
|
||||
input.removeAttribute('data-esun-original-qty');
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
<?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-coupons-link">
|
||||
<arguments>
|
||||
<argument name="path" xsi:type="string">customer-coupon/account/index</argument>
|
||||
<argument name="label" xsi:type="string" translate="true">My Coupons</argument>
|
||||
<argument name="sortOrder" xsi:type="number">245</argument>
|
||||
</arguments>
|
||||
</block>
|
||||
</referenceBlock>
|
||||
</body>
|
||||
</page>
|
||||
@@ -0,0 +1,11 @@
|
||||
<?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_form_register">
|
||||
<arguments>
|
||||
<argument name="subscription_promotion" xsi:type="object">Esun\CustomerCoupon\ViewModel\RegistrationSubscriptionPromotion</argument>
|
||||
</arguments>
|
||||
</referenceBlock>
|
||||
</body>
|
||||
</page>
|
||||
@@ -0,0 +1,17 @@
|
||||
<?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_CustomerCoupon::css/coupons.css"/>
|
||||
</head>
|
||||
<body>
|
||||
<referenceContainer name="sidebar.additional" remove="true"/>
|
||||
<referenceContainer name="content">
|
||||
<block class="Esun\CustomerCoupon\Block\Account\Coupons"
|
||||
name="customer.coupons.list"
|
||||
cacheable="false"
|
||||
template="Esun_CustomerCoupon::account/coupons.phtml"/>
|
||||
</referenceContainer>
|
||||
</body>
|
||||
</page>
|
||||
@@ -0,0 +1,14 @@
|
||||
<?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_CustomerCoupon::css/coupons.css"/>
|
||||
</head>
|
||||
<body>
|
||||
<referenceContainer name="before.body.end">
|
||||
<block class="Magento\Framework\View\Element\Template"
|
||||
name="esun.customer.coupon.picker"
|
||||
template="Esun_CustomerCoupon::picker/modal.phtml"/>
|
||||
</referenceContainer>
|
||||
</body>
|
||||
</page>
|
||||
@@ -0,0 +1,68 @@
|
||||
<?php
|
||||
/** @var \Esun\CustomerCoupon\Block\Account\Coupons $block */
|
||||
/** @var \Magento\Framework\Escaper $escaper */
|
||||
$available = $block->getAvailableCoupons();
|
||||
$unavailable = $block->getUnavailableCoupons();
|
||||
?>
|
||||
<div class="customer-coupons" data-mage-init='{"Esun_CustomerCoupon/js/account-coupons":{}}'>
|
||||
<div class="customer-coupons__tabs" role="tablist" aria-label="<?= $escaper->escapeHtmlAttr(__('Coupon status')) ?>">
|
||||
<button class="customer-coupons__tab is-active" type="button" role="tab" aria-selected="true"
|
||||
data-coupon-tab="available">
|
||||
<?= $escaper->escapeHtml(__('Available')) ?>
|
||||
<span>(<?= count($available) ?>)</span>
|
||||
</button>
|
||||
<button class="customer-coupons__tab" type="button" role="tab" aria-selected="false"
|
||||
data-coupon-tab="unavailable">
|
||||
<?= $escaper->escapeHtml(__('Unavailable')) ?>
|
||||
<span>(<?= count($unavailable) ?>)</span>
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<?php foreach (['available' => $available, 'unavailable' => $unavailable] as $status => $coupons): ?>
|
||||
<section class="customer-coupons__panel<?= $status === 'available' ? ' is-active' : '' ?>"
|
||||
data-coupon-panel="<?= $escaper->escapeHtmlAttr($status) ?>"
|
||||
<?= $status !== 'available' ? 'hidden' : '' ?>>
|
||||
<?php if (!$coupons): ?>
|
||||
<div class="customer-coupons__empty">
|
||||
<span class="customer-coupons__empty-icon" aria-hidden="true">%</span>
|
||||
<p><?= $escaper->escapeHtml(
|
||||
$status === 'available' ? __('No available coupons') : __('No unavailable coupons')
|
||||
) ?></p>
|
||||
</div>
|
||||
<?php else: ?>
|
||||
<div class="customer-coupons__grid">
|
||||
<?php foreach ($coupons as $coupon): ?>
|
||||
<article class="customer-coupon-card is-<?= $escaper->escapeHtmlAttr($status) ?>">
|
||||
<div class="customer-coupon-card__discount">
|
||||
<?= $escaper->escapeHtml($coupon['discount_label']) ?>
|
||||
</div>
|
||||
<div class="customer-coupon-card__body">
|
||||
<h3><?= $escaper->escapeHtml($coupon['rule_name']) ?></h3>
|
||||
<div class="customer-coupon-card__code">
|
||||
<?= $escaper->escapeHtml($coupon['code']) ?>
|
||||
</div>
|
||||
<?php if ($coupon['conditions']): ?>
|
||||
<ul>
|
||||
<?php foreach ($coupon['conditions'] as $condition): ?>
|
||||
<li><?= $escaper->escapeHtml($condition) ?></li>
|
||||
<?php endforeach; ?>
|
||||
</ul>
|
||||
<?php endif; ?>
|
||||
<div class="customer-coupon-card__meta">
|
||||
<?php if ($coupon['expires_at']): ?>
|
||||
<span><?= $escaper->escapeHtml(__('Valid through %1', $coupon['expires_at'])) ?></span>
|
||||
<?php else: ?>
|
||||
<span><?= $escaper->escapeHtml(__('No expiration date')) ?></span>
|
||||
<?php endif; ?>
|
||||
<?php if ($coupon['status_reason']): ?>
|
||||
<strong><?= $escaper->escapeHtml($coupon['status_reason']) ?></strong>
|
||||
<?php endif; ?>
|
||||
</div>
|
||||
</div>
|
||||
</article>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
<?php endif; ?>
|
||||
</section>
|
||||
<?php endforeach; ?>
|
||||
</div>
|
||||
@@ -0,0 +1,22 @@
|
||||
<?php
|
||||
/** @var \Magento\Framework\View\Element\Template $block */
|
||||
/** @var \Magento\Framework\Escaper $escaper */
|
||||
?>
|
||||
<div id="customer-coupon-picker"
|
||||
class="customer-coupon-picker"
|
||||
style="display:none"
|
||||
data-mage-init='<?= /* @noEscape */ json_encode([
|
||||
'Esun_CustomerCoupon/js/coupon-picker' => [
|
||||
'listUrl' => $block->getUrl('customer-coupon/ajax/list'),
|
||||
'loginUrl' => $block->getUrl('customer/account/login'),
|
||||
],
|
||||
]) ?>'>
|
||||
<div class="customer-coupon-picker__message" data-role="coupon-picker-message" hidden></div>
|
||||
<div class="customer-coupon-picker__loading" data-role="coupon-picker-loading" hidden>
|
||||
<?= $escaper->escapeHtml(__('Loading your coupons...')) ?>
|
||||
</div>
|
||||
<div class="customer-coupon-picker__empty" data-role="coupon-picker-empty" hidden>
|
||||
<?= $escaper->escapeHtml(__('No coupons are available for the current cart.')) ?>
|
||||
</div>
|
||||
<div class="customer-coupon-picker__list" data-role="coupon-picker-list"></div>
|
||||
</div>
|
||||
@@ -0,0 +1,276 @@
|
||||
.customer-coupons {
|
||||
padding: 4px 0 40px;
|
||||
}
|
||||
|
||||
.customer-coupons__tabs {
|
||||
display: flex;
|
||||
gap: 34px;
|
||||
margin-bottom: 28px;
|
||||
border-bottom: 1px solid #d9dddf;
|
||||
}
|
||||
|
||||
.customer-coupons__tab {
|
||||
position: relative;
|
||||
padding: 12px 0 14px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #777;
|
||||
font-size: 18px;
|
||||
font-weight: 600;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.customer-coupons__tab:hover,
|
||||
.customer-coupons__tab:focus,
|
||||
.customer-coupons__tab:active {
|
||||
border: 0 !important;
|
||||
background: transparent !important;
|
||||
color: #777;
|
||||
box-shadow: none !important;
|
||||
}
|
||||
|
||||
.customer-coupons__tab.is-active:hover,
|
||||
.customer-coupons__tab.is-active:focus,
|
||||
.customer-coupons__tab.is-active:active {
|
||||
color: #18a957;
|
||||
}
|
||||
|
||||
.customer-coupons__tab.is-active {
|
||||
color: #18a957;
|
||||
}
|
||||
|
||||
.customer-coupons__tab.is-active::after {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: -1px;
|
||||
left: 0;
|
||||
height: 3px;
|
||||
background: #18a957;
|
||||
content: "";
|
||||
}
|
||||
|
||||
.customer-coupons__grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.customer-coupons__panel[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.customer-coupon-card {
|
||||
display: grid;
|
||||
grid-template-columns: 150px minmax(0, 1fr);
|
||||
border: 1px solid #dce1e3;
|
||||
border-radius: 12px;
|
||||
background: #fff;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.customer-coupon-card__discount {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 24px 16px;
|
||||
background: #18a957;
|
||||
color: #fff;
|
||||
font-size: 23px;
|
||||
font-weight: 700;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.customer-coupon-card.is-unavailable {
|
||||
opacity: .68;
|
||||
}
|
||||
|
||||
.customer-coupon-card.is-unavailable .customer-coupon-card__discount {
|
||||
background: #8d9498;
|
||||
}
|
||||
|
||||
.customer-coupon-card__body {
|
||||
min-width: 0;
|
||||
padding: 22px 24px;
|
||||
}
|
||||
|
||||
.customer-coupon-card__body h3 {
|
||||
margin: 0 0 8px;
|
||||
font-size: 19px;
|
||||
}
|
||||
|
||||
.customer-coupon-card__code {
|
||||
margin-bottom: 12px;
|
||||
color: #18a957;
|
||||
font-family: monospace;
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
|
||||
.customer-coupon-card__body ul {
|
||||
margin: 0 0 14px 12px;
|
||||
color: #666;
|
||||
padding-inline-start: 0;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.customer-coupon-card__body ul li{
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.customer-coupon-card__meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: space-between;
|
||||
gap: 8px 16px;
|
||||
color: #747a7d;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.customer-coupon-card__meta strong {
|
||||
color: #b23b3b;
|
||||
}
|
||||
|
||||
.customer-coupons__empty {
|
||||
display: flex;
|
||||
min-height: 330px;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: #8a9093;
|
||||
}
|
||||
|
||||
.customer-coupons__empty-icon {
|
||||
display: flex;
|
||||
width: 92px;
|
||||
height: 62px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 8px;
|
||||
background: #e3e5e6;
|
||||
color: #aeb3b5;
|
||||
font-size: 36px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.customer-coupons__grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.customer-coupon-card {
|
||||
grid-template-columns: 110px minmax(0, 1fr);
|
||||
}
|
||||
|
||||
.customer-coupon-card__discount {
|
||||
font-size: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
.customer-coupon-picker-modal .modal-inner-wrap {
|
||||
width: calc(100% - 40px);
|
||||
max-width: 960px;
|
||||
}
|
||||
|
||||
.customer-coupon-picker__loading,
|
||||
.customer-coupon-picker__empty,
|
||||
.customer-coupon-picker__message {
|
||||
padding: 34px 12px;
|
||||
color: #6e7477;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.customer-coupon-picker__message.is-error {
|
||||
color: #b3261e;
|
||||
}
|
||||
|
||||
.customer-coupon-picker__list {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(min(100%, 360px), 1fr));
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.customer-coupon-picker__item {
|
||||
width: 100%;
|
||||
grid-template-columns: 110px minmax(0, 1fr);
|
||||
cursor: pointer;
|
||||
transition: border-color .2s ease, box-shadow .2s ease, opacity .2s ease;
|
||||
}
|
||||
|
||||
.customer-coupon-picker__item .customer-coupon-card__discount {
|
||||
padding: 20px 12px;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.customer-coupon-picker__item .customer-coupon-card__body {
|
||||
padding: 18px 16px;
|
||||
}
|
||||
|
||||
.customer-coupon-picker__item .customer-coupon-card__body h3 {
|
||||
font-size: 17px;
|
||||
}
|
||||
|
||||
.customer-coupon-picker__item:not(.is-applied):hover,
|
||||
.customer-coupon-picker__item:not(.is-applied):focus {
|
||||
border-color: #18a957;
|
||||
box-shadow: 0 4px 14px rgb(24 169 87 / 16%);
|
||||
outline: 0;
|
||||
}
|
||||
|
||||
.customer-coupon-picker__item.is-applied {
|
||||
cursor: default;
|
||||
opacity: .72;
|
||||
}
|
||||
|
||||
.customer-coupon-picker__item.is-applied .customer-coupon-card__meta strong {
|
||||
color: #168b4b;
|
||||
}
|
||||
|
||||
.customer-coupon-picker__item.is-loading {
|
||||
cursor: wait;
|
||||
opacity: .55;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
@media (max-width: 767px) {
|
||||
.customer-coupon-picker__list {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
}
|
||||
|
||||
.esun-coupon__picker-button {
|
||||
flex: 0 0 auto;
|
||||
min-width: 108px;
|
||||
height: 40px;
|
||||
padding: 0 14px;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: #168b4b;
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
text-decoration: underline;
|
||||
white-space: nowrap;
|
||||
box-shadow: none;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.esun-coupon__picker-button:hover,
|
||||
.esun-coupon__picker-button:focus,
|
||||
.esun-coupon__picker-button:active {
|
||||
border: 0 !important;
|
||||
background: transparent !important;
|
||||
color: #168b4b;
|
||||
box-shadow: none !important;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.checkout-cart-index .esun-coupon__picker-button {
|
||||
height: 46px;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.esun-coupon__applied .esun-coupon__picker-button {
|
||||
margin-left: auto;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
define(['jquery'], function ($) {
|
||||
'use strict';
|
||||
|
||||
return function (config, element) {
|
||||
var $root = $(element);
|
||||
|
||||
$root.on('click', '[data-coupon-tab]', function () {
|
||||
var status = $(this).attr('data-coupon-tab');
|
||||
|
||||
$root.find('[data-coupon-tab]')
|
||||
.removeClass('is-active')
|
||||
.attr('aria-selected', 'false');
|
||||
$(this).addClass('is-active').attr('aria-selected', 'true');
|
||||
$root.find('[data-coupon-panel]').removeClass('is-active').prop('hidden', true);
|
||||
$root.find('[data-coupon-panel="' + status + '"]')
|
||||
.addClass('is-active')
|
||||
.prop('hidden', false);
|
||||
});
|
||||
};
|
||||
});
|
||||
@@ -0,0 +1,149 @@
|
||||
define([
|
||||
'jquery',
|
||||
'Magento_Ui/js/modal/modal',
|
||||
'Esun_Cart/js/model/coupon-service',
|
||||
'mage/translate'
|
||||
], function ($, modal, couponService) {
|
||||
'use strict';
|
||||
|
||||
return function (config, element) {
|
||||
var $modal = $(element),
|
||||
$list = $modal.find('[data-role="coupon-picker-list"]'),
|
||||
$loading = $modal.find('[data-role="coupon-picker-loading"]'),
|
||||
$empty = $modal.find('[data-role="coupon-picker-empty"]'),
|
||||
$message = $modal.find('[data-role="coupon-picker-message"]');
|
||||
|
||||
modal({
|
||||
type: 'popup',
|
||||
title: $.mage.__('My Coupons'),
|
||||
modalClass: 'customer-coupon-picker-modal',
|
||||
responsive: true,
|
||||
innerScroll: true,
|
||||
buttons: []
|
||||
}, $modal);
|
||||
|
||||
$(document).on('click.esunCustomerCoupon', '[data-role="open-coupon-picker"]', function (event) {
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
$modal.modal('openModal');
|
||||
loadCoupons();
|
||||
});
|
||||
|
||||
$modal.on('click', '[data-role="apply-customer-coupon"]', function () {
|
||||
applyCoupon($(this));
|
||||
});
|
||||
|
||||
$modal.on('keydown', '[data-role="apply-customer-coupon"]', function (event) {
|
||||
if (event.key === 'Enter' || event.key === ' ') {
|
||||
event.preventDefault();
|
||||
applyCoupon($(this));
|
||||
}
|
||||
});
|
||||
|
||||
function applyCoupon($item) {
|
||||
var code = String($item.attr('data-coupon-code') || '');
|
||||
|
||||
if (!code || $item.attr('aria-disabled') === 'true' || $item.hasClass('is-loading')) {
|
||||
return;
|
||||
}
|
||||
$item.addClass('is-loading').attr('aria-busy', 'true');
|
||||
showMessage('', false);
|
||||
couponService.apply(code).done(function (response) {
|
||||
if (!response || !response.success) {
|
||||
showMessage(response && response.message
|
||||
? response.message
|
||||
: $.mage.__('We could not apply this coupon.'), true);
|
||||
return;
|
||||
}
|
||||
$modal.modal('closeModal');
|
||||
$(document).trigger('esun:customerCouponApplied', [response]);
|
||||
}).fail(function (xhr) {
|
||||
var response = xhr.responseJSON || {};
|
||||
showMessage(response.message || $.mage.__('We could not apply this coupon.'), true);
|
||||
}).always(function () {
|
||||
$item.removeClass('is-loading').removeAttr('aria-busy');
|
||||
});
|
||||
}
|
||||
|
||||
function loadCoupons() {
|
||||
$list.empty();
|
||||
$empty.prop('hidden', true);
|
||||
showMessage('', false);
|
||||
$loading.prop('hidden', false);
|
||||
|
||||
$.ajax({url: config.listUrl, type: 'get', dataType: 'json', cache: false})
|
||||
.done(function (response) {
|
||||
var coupons = response && response.coupons ? response.coupons : [],
|
||||
currentCouponCode = String(response && response.current_coupon_code || '');
|
||||
|
||||
if (!coupons.length) {
|
||||
$empty.prop('hidden', false);
|
||||
return;
|
||||
}
|
||||
$.each(coupons, function (index, coupon) {
|
||||
$list.append(renderCoupon(coupon, currentCouponCode));
|
||||
});
|
||||
})
|
||||
.fail(function (xhr) {
|
||||
var response = xhr.responseJSON || {};
|
||||
|
||||
if (xhr.status === 401) {
|
||||
window.location.href = config.loginUrl;
|
||||
return;
|
||||
}
|
||||
showMessage(response.message || $.mage.__('We could not load your coupons.'), true);
|
||||
})
|
||||
.always(function () {
|
||||
$loading.prop('hidden', true);
|
||||
});
|
||||
}
|
||||
|
||||
function renderCoupon(coupon, currentCouponCode) {
|
||||
var $item,
|
||||
$body = $('<div></div>', {'class': 'customer-coupon-card__body'}),
|
||||
$conditions = $('<ul></ul>'),
|
||||
$meta = $('<div></div>', {'class': 'customer-coupon-card__meta'}),
|
||||
isApplied = String(coupon.code) === currentCouponCode;
|
||||
|
||||
$item = $('<article></article>', {
|
||||
'class': 'customer-coupon-card customer-coupon-picker__item is-available' +
|
||||
(isApplied ? ' is-applied' : ''),
|
||||
role: 'button',
|
||||
tabindex: isApplied ? '-1' : '0',
|
||||
'aria-disabled': isApplied ? 'true' : 'false',
|
||||
'data-role': 'apply-customer-coupon',
|
||||
'data-coupon-code': coupon.code
|
||||
});
|
||||
$('<div></div>', {'class': 'customer-coupon-card__discount'})
|
||||
.text(coupon.discount_label).appendTo($item);
|
||||
$('<h3></h3>').text(coupon.rule_name).appendTo($body);
|
||||
$('<div></div>', {'class': 'customer-coupon-card__code'})
|
||||
.text(coupon.code).appendTo($body);
|
||||
$.each(coupon.conditions || [], function (index, condition) {
|
||||
$('<li></li>').text(condition).appendTo($conditions);
|
||||
});
|
||||
if ($conditions.children().length) {
|
||||
$conditions.appendTo($body);
|
||||
}
|
||||
$('<span></span>')
|
||||
.text(coupon.expires_at
|
||||
? $.mage.__('Valid through') + ' ' + coupon.expires_at
|
||||
: $.mage.__('No expiration date'))
|
||||
.appendTo($meta);
|
||||
if (isApplied) {
|
||||
$('<strong></strong>').text($.mage.__('Applied')).appendTo($meta);
|
||||
}
|
||||
$meta.appendTo($body);
|
||||
$body.appendTo($item);
|
||||
|
||||
return $item;
|
||||
}
|
||||
|
||||
function showMessage(text, isError) {
|
||||
$message
|
||||
.text(text)
|
||||
.toggleClass('is-error', Boolean(isError))
|
||||
.prop('hidden', !text);
|
||||
}
|
||||
};
|
||||
});
|
||||
Reference in New Issue
Block a user