Commit 40c87890 by halweg

feat : 订阅邮箱保存

parent 466b3105
<?php
/**
*
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
namespace Joshine\CouponPusher\Controller\Ajax;
use Magento\Customer\Api\AccountManagementInterface as CustomerAccountManagement;
use Magento\Customer\Model\Session;
use Magento\Customer\Model\Url as CustomerUrl;
use Magento\Framework\App\Action\Context;
use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\ObjectManager;
use Magento\Framework\Controller\Result\Redirect;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Phrase;
use Magento\Framework\Validator\EmailAddress as EmailValidator;
use Magento\Newsletter\Controller\Subscriber as SubscriberController;
use Magento\Newsletter\Model\Subscriber;
use Magento\Newsletter\Model\SubscriptionManagerInterface;
use Magento\Store\Model\ScopeInterface;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Newsletter\Model\SubscriberFactory;
use Magento\Framework\Controller\Result\JsonFactory;
/**
* New newsletter subscription action
*
* @SuppressWarnings(PHPMD.CouplingBetweenObjects)
*/
class Subscribe extends SubscriberController implements HttpPostActionInterface
{
/**
* @var CustomerAccountManagement
*/
protected $customerAccountManagement;
/**
* @var EmailValidator
*/
private $emailValidator;
/**
* @var SubscriptionManagerInterface
*/
private $subscriptionManager;
private $resultJsonFactory;
/**
* Initialize dependencies.
*
* @param Context $context
* @param SubscriberFactory $subscriberFactory
* @param Session $customerSession
* @param StoreManagerInterface $storeManager
* @param CustomerUrl $customerUrl
* @param CustomerAccountManagement $customerAccountManagement
* @param SubscriptionManagerInterface $subscriptionManager
* @param EmailValidator $emailValidator
*/
public function __construct(
Context $context,
SubscriberFactory $subscriberFactory,
Session $customerSession,
StoreManagerInterface $storeManager,
CustomerUrl $customerUrl,
CustomerAccountManagement $customerAccountManagement,
SubscriptionManagerInterface $subscriptionManager,
EmailValidator $emailValidator = null,
JsonFactory $jsonFactory
) {
$this->customerAccountManagement = $customerAccountManagement;
$this->subscriptionManager = $subscriptionManager;
$this->emailValidator = $emailValidator ?: ObjectManager::getInstance()->get(EmailValidator::class);
$this->resultJsonFactory = $jsonFactory;
parent::__construct(
$context,
$subscriberFactory,
$customerSession,
$storeManager,
$customerUrl
);
}
/**
* Validates that the email address isn't being used by a different account.
*
* @param string $email
* @throws LocalizedException
* @return void
*/
protected function validateEmailAvailable($email)
{
$websiteId = $this->_storeManager->getStore()->getWebsiteId();
if ($this->_customerSession->isLoggedIn()
&& ($this->_customerSession->getCustomerDataObject()->getEmail() !== $email
&& !$this->customerAccountManagement->isEmailAvailable($email, $websiteId))
) {
throw new LocalizedException(
__('This email address is already assigned to another user.')
);
}
}
/**
* Validates that if the current user is a guest, that they can subscribe to a newsletter.
*
* @throws LocalizedException
* @return void
*/
protected function validateGuestSubscription()
{
if ($this->_objectManager->get(ScopeConfigInterface::class)
->getValue(
Subscriber::XML_PATH_ALLOW_GUEST_SUBSCRIBE_FLAG,
ScopeInterface::SCOPE_STORE
) != 1
&& !$this->_customerSession->isLoggedIn()
) {
throw new LocalizedException(
__(
'Sorry, but the administrator denied subscription for guests. Please <a href="%1">register</a>.',
$this->_customerUrl->getRegisterUrl()
)
);
}
}
/**
* Validates the format of the email address
*
* @param string $email
* @throws LocalizedException
* @return void
*/
protected function validateEmailFormat($email)
{
if (!$this->emailValidator->isValid($email)) {
throw new LocalizedException(__('Please enter a valid email address.'));
}
}
/**
* New subscription action
*
* @return Redirect
*/
public function execute()
{
$message = [
'error' => __('Sorry. There is a problem with your Request.')
];
if ($this->getRequest()->isPost() && $this->getRequest()->getPost('email')) {
$email = (string)$this->getRequest()->getPost('email');
try {
$this->validateEmailFormat($email);
$this->validateGuestSubscription();
$this->validateEmailAvailable($email);
$websiteId = (int)$this->_storeManager->getStore()->getWebsiteId();
/** @var Subscriber $subscriber */
$subscriber = $this->_subscriberFactory->create()->loadBySubscriberEmail($email, $websiteId);
if ($subscriber->getId()
&& (int)$subscriber->getSubscriberStatus() === Subscriber::STATUS_SUBSCRIBED) {
throw new LocalizedException(
__('This email address is already subscribed.')
);
}
$storeId = (int)$this->_storeManager->getStore()->getId();
$currentCustomerId = $this->getSessionCustomerId($email);
$subscriber = $currentCustomerId
? $this->subscriptionManager->subscribeCustomer($currentCustomerId, $storeId)
: $this->subscriptionManager->subscribe($email, $storeId);
$message = $this->getSuccessMessage((int)$subscriber->getSubscriberStatus());
$message = [
'success' => __('Success.'),
'data' => $message,
];
} catch (LocalizedException $e) {
$message = ['error' => $e->getMessage()];
} catch (\Exception $e) {
$message = ['error' => $e->getMessage()];
$this->logger->error($e->getMessage());
}
}
$resultPage = $this->resultJsonFactory->create();
$resultPage->setHttpResponseCode(200);
$resultPage->setData($message);
return $resultPage;
}
/**
* Get customer id from session if he is owner of the email
*
* @param string $email
* @return int|null
*/
private function getSessionCustomerId(string $email): ?int
{
if (!$this->_customerSession->isLoggedIn()) {
return null;
}
$customer = $this->_customerSession->getCustomerDataObject();
if ($customer->getEmail() !== $email) {
return null;
}
return (int)$this->_customerSession->getId();
}
/**
* Get success message
*
* @param int $status
* @return Phrase
*/
private function getSuccessMessage(int $status): Phrase
{
if ($status === Subscriber::STATUS_NOT_ACTIVE) {
return __('The confirmation request has been sent.');
}
return __('Thank you for your subscription.');
}
}
...@@ -3,6 +3,21 @@ ...@@ -3,6 +3,21 @@
* @var $block \Joshine\CouponPusher\Block\CouponSubscribeAlert * @var $block \Joshine\CouponPusher\Block\CouponSubscribeAlert
*/ */
?> ?>
<style>
.coupon-input-errorMsg {
height: 12px;
font-size: 12px;
color: #fa320f;
line-height: 12px;
font-weight: 400;
text-align: left;
width: 446px;
margin-top: 10px;
display: none;
align-items: center;
position: relative;
}
</style>
<div class="joshine-model-warp" id="coupon-subscribe-alert" style="display: none;"> <div class="joshine-model-warp" id="coupon-subscribe-alert" style="display: none;">
<div class="joshine-mask"></div> <div class="joshine-mask"></div>
<div class="j-modal j-modal-vertical"> <div class="j-modal j-modal-vertical">
...@@ -15,6 +30,7 @@ ...@@ -15,6 +30,7 @@
<div class="coupon-alt joshine-text-center"> <div class="coupon-alt joshine-text-center">
<img src="<?= $block->getViewFileUrl('Joshine_CouponPusher::images/coupon_background.png'); ?>" alt="" class=""> <img src="<?= $block->getViewFileUrl('Joshine_CouponPusher::images/coupon_background.png'); ?>" alt="" class="">
<div class="coupon-text"> <div class="coupon-text">
<!--todo:: show config coupon-->
<p class="coupon-discount-amount">20% OFF</p> <p class="coupon-discount-amount">20% OFF</p>
<p class="coupon-discount-rule">testtest</p> <p class="coupon-discount-rule">testtest</p>
</div> </div>
...@@ -23,10 +39,11 @@ ...@@ -23,10 +39,11 @@
</div> </div>
<div class="coupon-alt-input"> <div class="coupon-alt-input">
<div class="coupon-alt-input-left"> <div class="coupon-alt-input-left">
<input placeholder="Enter your email address" type="email" value=""> <input placeholder="Enter your email address" type="email" id="coupon-subscribe-email-input" value="">
</div> </div>
<div class="coupon-alert-submit-button"><?= __('Submit') ?></div> <div class="coupon-alert-submit-button" id="coupon-subscribe-email"><?= __('Submit') ?></div>
</div> </div>
<div class="coupon-input-errorMsg"></div>
<div class="split-line"><span class="split-text"><?= __('OR') ?></span></div> <div class="split-line"><span class="split-text"><?= __('OR') ?></span></div>
<div class="coupon-alt-bottom-title"><span><?= __('Submit email address to get your exclusive offer.') ?></span> <div class="coupon-alt-bottom-title"><span><?= __('Submit email address to get your exclusive offer.') ?></span>
</div> </div>
...@@ -53,6 +70,39 @@ ...@@ -53,6 +70,39 @@
$(document).on('click', '#coupon-alert-close', function () { $(document).on('click', '#coupon-alert-close', function () {
$('#coupon-subscribe-alert').hide(); $('#coupon-subscribe-alert').hide();
}); });
$(document).on('click', "#coupon-subscribe-email", function(e){
var email = $("#coupon-subscribe-email-input").val();
if (email.length < 5) {
$(".coupon-input-errorMsg").html('You enter an invalid email address').show();
return;
}
var data = {
email : email
};
$.ajax({
url: '/joshine_coupon_pusher/ajax/subscribe',
data: data,
type: 'POST',
dataType: 'json',
success: function (response) {
if (response.hasOwnProperty('error')) {
$(".coupon-input-errorMsg").html(response.error).show();
return;
}
//todo::show coupon code
},
error: function () {
$(".coupon-input-errorMsg").html('error').show();
},
});
})
$(document).on('keyup','#coupon-subscribe-email-input', function(e){
$(".coupon-input-errorMsg").hide();
})
}) })
</script> </script>
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment