Skip to content

Commit

Permalink
Merge pull request #59 from Frendino/master
Browse files Browse the repository at this point in the history
SAIL-18: RMAs emails not working through Sailthru
  • Loading branch information
lindsaycooper committed Jan 31, 2020
2 parents 177013f + bf24e60 commit b349301
Show file tree
Hide file tree
Showing 17 changed files with 383 additions and 64 deletions.
7 changes: 7 additions & 0 deletions Helper/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ class Settings extends AbstractHelper
const XML_ORDER_TEMPLATE = "magesail_send/transactionals/purchase_template";
const LO_ABANDONED_CART_ENABLED = "1";

const XML_TEMPLATES_CACHE_LIFETIME = "magesail_send/transactionals/templates_cache_lifetime";

/** Path to the `transactionals` tab. */
const XML_TRANSACTIONALS_PATH = 'magesail_send/transactionals/';

Expand Down Expand Up @@ -156,6 +158,11 @@ public function getTransactionalsEnabled($storeId = null)
return boolval($this->getSettingsVal(self::XML_TRANSACTIONALS_ENABLED, $storeId));
}

public function getTemplatesCacheLifetime($storeId = null)
{
return $this->getSettingsVal(self::XML_TEMPLATES_CACHE_LIFETIME, $storeId);
}

public function getSender($storeId = null)
{
return $this->getSettingsVal(self::XML_TRANSACTIONALS_SENDER, $storeId);
Expand Down
27 changes: 18 additions & 9 deletions Helper/Templates.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Sailthru\MageSail\Logger;
use Sailthru\MageSail\Model\Config\Template\Data as TemplateConfig;
use Sailthru\MageSail\Model\Template as TemplateModel;
use Sailthru\MageSail\Model\SailthruTemplates;

class Templates extends AbstractHelper {

Expand All @@ -17,6 +18,9 @@ class Templates extends AbstractHelper {
/** @var ClientManager */
private $clientManager;

/** @var SailthruTemplates */
protected $sailthruTemplates;

public function __construct(
Context $context,
StoreManager $storeManager,
Expand All @@ -25,24 +29,29 @@ public function __construct(
TemplateConfig $templateConfig,
ObjectManagerInterface $objectManager,
ScopeResolver $scopeResolver,
ClientManager $clientManager
ClientManager $clientManager,
SailthruTemplates $sailthruTemplates
) {
parent::__construct($context, $storeManager, $logger, $templateModel, $templateConfig, $objectManager, $scopeResolver);
$this->clientManager = $clientManager;
$this->sailthruTemplates = $sailthruTemplates;
}

public function getSailthruTemplates($storeId = null)
{
if (empty($this->sailthruTemplates) or !isset($this->sailthruTemplates[$storeId])) {
$client = $this->clientManager->getClient(true, $storeId);
try {
$this->templates[$storeId] = $client->getTemplates();
} catch (\Sailthru_Client_Exception $ex) {
$this->logger->err("Exception getting templates: {$ex->getMessage()}");
}
if (!empty($this->templates[$storeId])) {
return $this->templates[$storeId];
}

return $this->templates[$storeId];
try {
$this->templates[$storeId] = $this->sailthruTemplates->getTemplatesByStoreId($storeId);

return $this->templates[$storeId];
} catch (\Sailthru_Client_Exception $ex) {
$this->logger->err("Exception getting templates: {$ex->getMessage()}");

return [];
}
}

public function templateExists($templateIdentifier, $storeId = null)
Expand Down
14 changes: 13 additions & 1 deletion Mail/Message.php → Mail/EmailMessage.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

namespace Sailthru\MageSail\Mail;

class Message extends \Magento\Framework\Mail\Message
class EmailMessage extends \Magento\Framework\Mail\EmailMessage
{
/**
* Template info.
Expand Down Expand Up @@ -38,4 +38,16 @@ public function setTemplateInfo(array $info)

return false;
}

/**
* Get decoded MIME body text
*
* @return string
*/
public function getDecodedBodyText()
{
return !empty($this->getBody()) && !empty($this->getBody()->getParts()[0])
? $this->getBody()->getParts()[0]->getRawContent()
: '';
}
}
2 changes: 1 addition & 1 deletion Mail/Template.php
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ public function loadDefault($templateId)
if (count($directiveString) < 2) {
continue;
}

$directiveString[0] = trim(preg_replace('/(]\)|")/', '', $directiveString[0]));

$this->templateDirectives[strtolower(str_replace(' ', '_', $directiveString[1]))] = str_replace(
Expand Down
45 changes: 21 additions & 24 deletions Mail/Transport.php
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
<?php
namespace Sailthru\MageSail\Mail;

use Magento\Framework\App\Config\ScopeConfigInterface;
use Magento\Framework\App\RequestInterface;
use Magento\Framework\Exception\MailException;
use Magento\Framework\Mail\MessageInterface;
use Magento\Framework\Exception\RuntimeException;
use Magento\Framework\Mail\EmailMessageInterface;
use Magento\Store\Model\StoreManagerInterface;
use Sailthru\MageSail\Helper\ClientManager;
use Sailthru\MageSail\Helper\Settings;
Expand All @@ -14,7 +16,7 @@
use Zend\Mail\Address\AddressInterface;
use Zend\Mail\Header\HeaderInterface;

class Transport extends \Magento\Framework\Mail\Transport implements \Magento\Framework\Mail\TransportInterface
class Transport extends \Magento\Email\Model\Transport
{
/** @var ClientManager */
protected $clientManager;
Expand All @@ -39,7 +41,8 @@ class Transport extends \Magento\Framework\Mail\Transport implements \Magento\Fr
*
* @param ClientManager $clientManager
* @param Settings $sailthruSettings
* @param MessageInterface $message
* @param EmailMessageInterface $message
* @param ScopeConfigInterface $scopeConfig
* @param SailthruTemplates $sailthruTemplates
* @param StoreManagerInterface $storeManager
* @param RequestInterface $request
Expand All @@ -48,7 +51,8 @@ class Transport extends \Magento\Framework\Mail\Transport implements \Magento\Fr
public function __construct(
ClientManager $clientManager,
Settings $sailthruSettings,
MessageInterface $message,
EmailMessageInterface $message,
ScopeConfigInterface $scopeConfig,
SailthruTemplates $sailthruTemplates,
StoreManagerInterface $storeManager,
RequestInterface $request,
Expand All @@ -59,7 +63,7 @@ public function __construct(
$this->sailthruTemplates = $sailthruTemplates;
$this->storeManager = $storeManager;
$this->request = $request;
parent::__construct($message, $parameters);
parent::__construct($message, $scopeConfig, $parameters);
}

/**
Expand Down Expand Up @@ -99,20 +103,10 @@ public function sendMessage()
public function sendViaAPI($templateData, $storeId)
{
$client = $this->clientManager->getClient(true, $storeId);
if (version_compare($this->sailthruSettings->getMagentoVersion(), '2.3.0', '<')) {
$message = $this->getMessage();
$to = $this->cleanEmails(implode(',', $message->getRecipients()));
$subject = $message->getSubject();
$body = $message->getBody()->getRawContent();
} else {
$message = ZendMessage::fromString($this->getMessage()->getRawMessage());
$to = $this->prepareRecipients($message);
$subject = $this->prepareSubject($message);
$body = $this->prepareBody($message);
}
$message = ZendMessage::fromString($this->getMessage()->getRawMessage());
$vars = [
"subj" => $subject,
"content" => $body,
"subj" => $this->prepareSubject($message),
"content" => $this->getMessage()->getDecodedBodyText(),
];

try {
Expand All @@ -131,8 +125,8 @@ public function sendViaAPI($templateData, $storeId)

$params = [
"template" => $templateName,
"email" => $to,
"vars" => $vars,
"email" => $this->prepareRecipients($message),
"vars" => $vars,
];

$response = $client->apiPost('send', $params);
Expand All @@ -149,16 +143,19 @@ public function sendViaAPI($templateData, $storeId)
* Prepare recipients list
*
* @param \Zend\Mail\Message $message
* @throws \Zend\Mail\Transport\Exception\RuntimeException
* @throws RuntimeException
*
* @return string
*
* @throws RuntimeException
*/
protected function prepareRecipients(\Zend\Mail\Message $message)
{
$headers = $message->getHeaders();

$hasTo = $headers->has('to');
if (!$hasTo && !$headers->has('cc') && !$headers->has('bcc')) {
throw new Exception\RuntimeException(
throw new RuntimeException(
'Invalid email; contains no at least one of "To", "Cc", and "Bcc" header'
);
}
Expand All @@ -171,11 +168,11 @@ protected function prepareRecipients(\Zend\Mail\Message $message)
$to = $headers->get('to');
$list = $to->getAddressList();
if (count($list) == 0) {
throw new Exception\RuntimeException('Invalid "To" header; contains no addresses');
throw new RuntimeException('Invalid "To" header; contains no addresses');
}

// If not on Windows, return normal string
if (! $this->isWindowsOs()) {
if (!$this->isWindowsOs() && version_compare($this->sailthruSettings->getMagentoVersion(), '2.3.3', '<')) {
return $to->getFieldValue(HeaderInterface::FORMAT_ENCODED);
}

Expand Down
62 changes: 36 additions & 26 deletions Mail/TransportBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,61 +2,71 @@

namespace Sailthru\MageSail\Mail;

use Magento\Framework\App\TemplateTypesInterface;
use Magento\Framework\Mail\MessageInterface;
use Sailthru\MageSail\Mail\EmailMessage;
use Magento\Framework\Mail\TemplateInterface;
use Magento\Newsletter\Model\Subscriber;
use Magento\Store\Api\Data\StoreInterface;

class TransportBuilder extends \Magento\Framework\Mail\Template\TransportBuilder
{
/** @var Message */
/** @var EmailMessage */
protected $message;

/** @var array */
protected $templateData;

/** @var TemplateInterface */
protected $template;

/**
* Prepare message
* Get template
*
* @return $this
* @throws \Magento\Framework\Exception\MailException
* @throws \Zend_Mail_Exception
* @return TemplateInterface
*
* @customization START
*/
protected function prepareMessage()
protected function getTemplate()
{
/** @var Template $template */
$template = $this->getTemplate();
$types = [
TemplateTypesInterface::TYPE_TEXT => MessageInterface::TYPE_TEXT,
TemplateTypesInterface::TYPE_HTML => MessageInterface::TYPE_HTML,
];
$this->template = parent::getTemplate();

$body = $template->processTemplate();
return $this->template;
}
/** @customization END */

/** @customization START */
$templateData = [
'variables' => $template->templateVariables ?: [],
/**
* Prepare message.
*
* @return TransportBuilder
*
* @throws \Magento\Framework\Exception\LocalizedException
*
* @customization START
*/
protected function prepareMessage()
{
parent::prepareMessage();
$this->templateData = [
'variables' => $this->template->templateVariables ?: [],
'identifier' => $this->templateIdentifier,
];

if (isset($this->templateVars['store'])){
/** @var StoreInterface $store */
$store = $this->templateVars['store'];
$templateData['storeId'] = $store->getId();
$this->templateData['storeId'] = $store->getId();
}

// Newsletter admin patch
if (isset($this->templateVars['subscriber'])) {
/** @var Subscriber $subscriber */
$subscriber = $this->templateVars['subscriber'];
$storeId = $subscriber->getStoreId();
$templateData['storeId'] = $storeId;
$this->templateData['storeId'] = $storeId;
}

$this->message->setTemplateInfo($templateData);
/** @customization END */

$this->message->setMessageType($types[$template->getType()])
->setBody($body)
->setSubject($template->getSubject());
$this->message->setTemplateInfo($this->templateData);

return $this;
}
/** @customization END */
}
25 changes: 25 additions & 0 deletions Model/Cron.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,11 @@ class Cron
*/
private $sailthruIntercept;

/**
* @var SailthruTemplates
*/
protected $sailthruTemplates;

/**
* @var StoreManagerInterface
*/
Expand All @@ -48,6 +53,7 @@ class Cron
* @param StoreManagerInterface $storeManager
* @param SailthruIntercept $sailthruIntercept
* @param SailthruProduct $sailthruProduct
* @param SailthruTemplates $sailthruTemplates
* @param FlagManager $flagManager
* @param Logger $logger
*/
Expand All @@ -56,12 +62,14 @@ public function __construct(
StoreManagerInterface $storeManager,
SailthruIntercept $sailthruIntercept,
SailthruProduct $sailthruProduct,
SailthruTemplates $sailthruTemplates,
FlagManager $flagManager,
Logger $logger
) {
$this->collectionFactory = $collectionFactory;
$this->sailthruProduct = $sailthruProduct;
$this->sailthruIntercept = $sailthruIntercept;
$this->sailthruTemplates = $sailthruTemplates;
$this->storeManager = $storeManager;
$this->flagManager = $flagManager;
$this->logger = $logger;
Expand Down Expand Up @@ -130,4 +138,21 @@ public function exportProducts()
return false;
}
}

/**
* Add Sailthru templates to cache
*/
public function syncSailthruTemplates()
{
try {
$storeIds = array_merge([null], array_keys($this->storeManager->getStores()));
foreach ($storeIds as $storeId) {
$this->sailthruTemplates->getTemplatesByStoreId($storeId);
}
} catch (\Exception $e) {
$this->logger->err('Cron Job sailthru_sync_templates - ' . $e->getMessage());
}

return $this;
}
}
Loading

0 comments on commit b349301

Please sign in to comment.