Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed basket category #1

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

Aktuální verzi pluginu lze stáhnout zde:

https://github.com/Ecomailcz/magento-2/releases/download/2.1.0/Ecomail_Ecomail_2.1.0.zip
https://github.com/JakubFilounek/magento-2/releases

# Instalace modulu

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<?php

namespace Ecomail\Ecomail\Block\System\Config\Form\Field;

use Ecomail\Ecomail\Helper\Data;
use Magento\Backend\Block\Template\Context;
use Magento\Config\Block\System\Config\Form\Field;
use Magento\Framework\Data\Form\Element\AbstractElement;
use Magento\Store\Model\StoreManagerInterface;

class Webhook extends Field
{
/**
* @var string
*/
protected $_template = 'Ecomail_Ecomail::system/config/form/field/webhook.phtml';

/**
* @var Data
*/
private $helper;

/**
* @var StoreManagerInterface
*/
private $storeManager;


/**
* @param Context $context
* @param Data $helper
* @param StoreManagerInterface $storeManager
* @param array $data
*/
public function __construct(
Context $context,
Data $helper,
StoreManagerInterface $storeManager,
array $data = []
) {
parent::__construct($context, $data);
$this->helper = $helper;
$this->storeManager = $storeManager;
}

/**
* @return string
*/
public function getWebhookUrl(): string
{
$baseUrl = $this->storeManager->getDefaultStoreView()->getBaseUrl();
return rtrim($baseUrl, '/') . '/ecomail/webhook/action/' . $this->helper->getWebhookHash() . '/';
}

/**
* Return element html
*
* @param AbstractElement $element
* @return string
*
*/
protected function _getElementHtml(AbstractElement $element): string
{
return $this->_toHtml();
}
}
4 changes: 4 additions & 0 deletions app/code/Ecomail/Ecomail/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,7 @@

## v2.1.0 - 2 Jun, 2023
* added Magento 2.4.6 compatibility

## v2.2.0 - 2 Jun, 2023
* added webhook for subscriber status synchronization
* fixed issue with duplicated subscribers
172 changes: 172 additions & 0 deletions app/code/Ecomail/Ecomail/Controller/Webhook/Action.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,172 @@
<?php
namespace Ecomail\Ecomail\Controller\Webhook;

use Magento\Framework\App\Action\HttpPostActionInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Controller\ResultFactory;
use Magento\Framework\Exception\AlreadyExistsException;
use Magento\Framework\Exception\LocalizedException;
use Magento\Framework\Filesystem\Driver\File;
use Magento\Framework\Serialize\Serializer\Json;
use Magento\Newsletter\Model\SubscriberFactory;
use Magento\Newsletter\Model\ResourceModel\Subscriber as SubscriberResource;
use Magento\Newsletter\Model\Subscriber;
use Magento\Store\Model\StoreManagerInterface;
use Magento\Framework\Exception\NotFoundException;
use Ecomail\Ecomail\Helper\Data;
use Psr\Log\LoggerInterface;

class Action implements HttpPostActionInterface
{
const REQUEST_SUBSCRIBE = 'SUBSCRIBED';
const REQUEST_UNSUBSCRIBE = 'UNSUBSCRIBED';

/** @var Data */
private $helper;

/** @var File */
private File $file;

/** @var LoggerInterface */
private $logger;

/** @var Json */
private $json;

/** @var ResultFactory */
private $resultFactory;

/** @var SubscriberFactory */
private $subscriberFactory;

/** @var SubscriberResource */
private $subscriberResource;

/** @var StoreManagerInterface */
private $storeManager;

/** @var RequestInterface */
private $httpRequest;

/**
* @param Data $helper
* @param Json $json
* @param File $file
* @param LoggerInterface $logger
* @param RequestInterface $httpRequest
* @param ResultFactory $resultFactory
* @param StoreManagerInterface $storeManager
* @param SubscriberFactory $subscriberFactory
* @param SubscriberResource $subscriberResource
*/
public function __construct(
Data $helper,
Json $json,
File $file,
LoggerInterface $logger,
RequestInterface $httpRequest,
ResultFactory $resultFactory,
StoreManagerInterface $storeManager,
SubscriberFactory $subscriberFactory,
SubscriberResource $subscriberResource
) {
$this->helper = $helper;
$this->json = $json;
$this->file = $file;
$this->logger = $logger;
$this->httpRequest = $httpRequest;
$this->resultFactory = $resultFactory;
$this->storeManager = $storeManager;
$this->subscriberFactory = $subscriberFactory;
$this->subscriberResource = $subscriberResource;
}

/**
* @inheritDoc
*/
public function execute()
{
$resultRaw = $this->resultFactory->create(ResultFactory::TYPE_RAW);

try {
$request = $this->readRequest();
if ($request['status'] == self::REQUEST_UNSUBSCRIBE) {
$this->unsubscribe($request['email']);
} elseif ($request['status'] == self::REQUEST_SUBSCRIBE) {
$this->subscribe($request['email']);
}
$resultRaw->setContents('SUCCESS');
} catch (\Exception $e) {
$this->logger->error('Ecomail webhook error: ' . $e->getMessage());
$resultRaw->setContents('ERROR')->setHttpResponseCode(400);
}

return $resultRaw;
}

/**
* @param string $email
* @return void
* @throws AlreadyExistsException
*/
private function unsubscribe(string $email)
{
$subscriber = $this->subscriberFactory->create()
->loadBySubscriberEmail($email, $this->storeManager->getDefaultStoreView()->getWebsiteId());

if (!$subscriber->getId()
|| $subscriber->getSubscriberStatus() == Subscriber::STATUS_UNSUBSCRIBED
) {
return;
}

$subscriber->setSubscriberStatus(Subscriber::STATUS_UNSUBSCRIBED);
$this->subscriberResource->save($subscriber);
}

/**
* @param string $email
* @return void
* @throws AlreadyExistsException
*/
private function subscribe(string $email)
{
$subscriber = $this->subscriberFactory->create()
->loadBySubscriberEmail($email, $this->storeManager->getDefaultStoreView()->getWebsiteId());

if (!$subscriber->getId()
|| $subscriber->getSubscriberStatus() == Subscriber::STATUS_SUBSCRIBED
) {
return;
}

$subscriber->setSubscriberStatus(Subscriber::STATUS_SUBSCRIBED);
$this->subscriberResource->save($subscriber);
}

/**
* @return array
* @throws LocalizedException
*/
private function readRequest()
{
$params = $this->httpRequest->getParams();
$keys = array_keys($params);
if (array_shift($keys) != $this->helper->getWebhookHash()) {
throw new NotFoundException(__('Invalid Webhook key.'));
}

if ($content = $this->file->fileGetContents('php://input')) {
try {
$request = $this->json->unserialize($content);
} catch (\InvalidArgumentException $e) {
throw new LocalizedException(__('Invalid request data, JSON unserialize error.'));
}

if (isset($request['payload'])) {
return $request['payload'];
}
}
throw new LocalizedException(__('Invalid request data.'));
}
}
51 changes: 51 additions & 0 deletions app/code/Ecomail/Ecomail/Helper/Data.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@

use Ecomail\Ecomail\Model\Config\Source\Address;
use Magento\Framework\App\Helper\AbstractHelper;
use Magento\Framework\App\Helper\Context;
use Magento\Store\Model\ScopeInterface;
use Magento\Framework\Flag\FlagResource;
use Magento\Framework\FlagFactory;

class Data extends AbstractHelper
{
Expand All @@ -24,6 +27,21 @@ class Data extends AbstractHelper
const XML_PATH_ECOMAIL_TRACKING_ENABLED = 'ecomail/tracking/enabled';
const XML_PATH_ECOMAIL_TRACKING_APP_ID = 'ecomail/tracking/app_id';

/**
* @param Context $context
* @param FlagFactory $flagFactory
* @param FlagResource $flagResource
*/
public function __construct(
Context $context,
FlagFactory $flagFactory,
FlagResource $flagResource
) {
parent::__construct($context);
$this->flagFactory = $flagFactory;
$this->flagResource = $flagResource;
}

/**
* @param null $store
* @return bool
Expand Down Expand Up @@ -203,4 +221,37 @@ public function getAppId($store = null)
$store
);
}

/**
* @return string
*/
public function getWebhookHash()
{
$flag = $this->getFlagObject('ecomail_webhook');
if ($data = $flag->getFlagData()) {
return $data;
}

$value = uniqid();

$flag->setFlagData($value);
$this->flagResource->save($flag);
return $value;
}

/**
* @param string $code
* @return \Magento\Framework\Flag
*/
private function getFlagObject($code)
{
$flag = $this->flagFactory->create(['data' => ['flag_code' => $code]]);
$this->flagResource->load(
$flag,
$code,
'flag_code'
);

return $flag;
}
}
2 changes: 1 addition & 1 deletion app/code/Ecomail/Ecomail/Model/Api.php
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ private function buildListUrl(string $path): string
private function getErrorMessage(array $response): Phrase
{
if (isset($response['message'])) {
return $response['message'];
return __($response['message']);
}

if (isset($response['errors'])) {
Expand Down
2 changes: 1 addition & 1 deletion app/code/Ecomail/Ecomail/Model/BasketEventMapper.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ public function map(Quote $quote): array
$data = [];
$data['event'] = [
'email' => $quote->getCustomerEmail(),
'category' => 'ua',
'category' => 'ue',
'action' => 'Basket',
'label' => 'Basket',
];
Expand Down
5 changes: 2 additions & 3 deletions app/code/Ecomail/Ecomail/Model/SubscriptionManager.php
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,8 @@ public function subscribeFromOrder(OrderInterface $order)
try {
if (!$this->subscriberExists($order->getCustomerEmail())) {
$this->createLocalSubscriber($order);
$this->api->addSubscriberToList($this->subscriberDataMapper->mapFromOrder($order));
}

$this->api->addSubscriberToList($this->subscriberDataMapper->mapFromOrder($order));
} catch (Exception $e) {
$this->logger->error('Failed to add Ecomail subscription.', [$e]);
}
Expand All @@ -109,7 +108,7 @@ public function subscriberExists(string $customerEmail): bool
$subscriber = $this->subscriberFactory->create();
$subscriber->loadByEmail($customerEmail);

return $subscriber->isSubscribed();
return $subscriber->getId() != null;
}

/**
Expand Down
Loading