diff --git a/Block/Adminhtml/System/Config/SyncCustomer.php b/Block/Adminhtml/System/Config/Sync.php similarity index 66% rename from Block/Adminhtml/System/Config/SyncCustomer.php rename to Block/Adminhtml/System/Config/Sync.php index cc57f16..a31bb17 100644 --- a/Block/Adminhtml/System/Config/SyncCustomer.php +++ b/Block/Adminhtml/System/Config/Sync.php @@ -21,23 +21,25 @@ namespace Mageplaza\Smtp\Block\Adminhtml\System\Config; +use Mageplaza\Smtp\Model\Config\Source\SyncType; + /** - * Class SyncCustomer + * Class Sync * @package Mageplaza\Smtp\Block\Adminhtml\System\Config */ -class SyncCustomer extends Button +class Sync extends Button { /** * @var string */ - protected $_template = 'system/config/sync-template.phtml'; + protected $_template = 'Mageplaza_Smtp::system/config/sync-template.phtml'; /** * @return string */ public function getEstimateUrl() { - return $this->getUrl('adminhtml/smtp_sync/estimatecustomer', ['_current' => true]); + return $this->getUrl('adminhtml/smtp_sync/estimate', ['_current' => true]); } /** @@ -57,11 +59,15 @@ public function getStoreId() } /** - * @return mixed + * @return array */ public function getSyncSuccessMessage() { - return __('Customer synchronization has been completed.'); + return [ + SyncType::CUSTOMERS => __('Customer synchronization has been completed.'), + SyncType::ORDERS => __('Order synchronization has been completed.'), + SyncType::SUBSCRIBERS => __('Subscriber synchronization has been completed.') + ]; } /** @@ -69,7 +75,7 @@ public function getSyncSuccessMessage() */ public function getElementId() { - return 'mp-sync-customer'; + return 'mp-synchronize'; } /** @@ -77,14 +83,6 @@ public function getElementId() */ public function getComponent() { - return 'Mageplaza_Smtp/js/sync/customer'; - } - - /** - * @return bool - */ - public function isRenderCss() - { - return true; + return 'Mageplaza_Smtp/js/sync/sync'; } } diff --git a/Block/Adminhtml/System/Config/SyncOrder.php b/Block/Adminhtml/System/Config/SyncOrder.php deleted file mode 100644 index d0b57f2..0000000 --- a/Block/Adminhtml/System/Config/SyncOrder.php +++ /dev/null @@ -1,90 +0,0 @@ -getUrl('adminhtml/smtp_sync/estimateorder', ['_current' => true]); - } - - /** - * @return mixed - */ - public function getWebsiteId() - { - return $this->getRequest()->getParam('website'); - } - - /** - * @return mixed - */ - public function getStoreId() - { - return $this->getRequest()->getParam('store'); - } - - /** - * @return mixed - */ - public function getSyncSuccessMessage() - { - return __('Order synchronization has been completed.'); - } - - /** - * @return string - */ - public function getElementId() - { - return 'mp-sync-order'; - } - - /** - * @return string - */ - public function getComponent() - { - return 'Mageplaza_Smtp/js/sync/order'; - } - - /** - * @return bool - */ - public function isRenderCss() - { - return false; - } -} diff --git a/Block/Adminhtml/System/Config/SyncSubscriber.php b/Block/Adminhtml/System/Config/SyncSubscriber.php deleted file mode 100755 index da61c07..0000000 --- a/Block/Adminhtml/System/Config/SyncSubscriber.php +++ /dev/null @@ -1,90 +0,0 @@ -getUrl('adminhtml/smtp_sync/estimatesubscriber', ['_current' => true]); - } - - /** - * @return mixed - */ - public function getWebsiteId() - { - return $this->getRequest()->getParam('website'); - } - - /** - * @return mixed - */ - public function getStoreId() - { - return $this->getRequest()->getParam('store'); - } - - /** - * @return mixed - */ - public function getSyncSuccessMessage() - { - return __('Subscriber synchronization has been completed.'); - } - - /** - * @return string - */ - public function getElementId() - { - return 'mp-sync-subscriber'; - } - - /** - * @return string - */ - public function getComponent() - { - return 'Mageplaza_Smtp/js/sync/subscriber'; - } - - /** - * @return bool - */ - public function isRenderCss() - { - return true; - } -} diff --git a/Block/Script.php b/Block/Script.php index f75d0f0..e42f4d3 100644 --- a/Block/Script.php +++ b/Block/Script.php @@ -22,10 +22,15 @@ namespace Mageplaza\Smtp\Block; use Magento\Catalog\Block\Product\Context; +use Magento\Customer\Model\Context as CustomerContext; +use Magento\Catalog\Helper\Data; +use Magento\Catalog\Model\Product; use Magento\Customer\Model\SessionFactory as CustomerSession; use Magento\Checkout\Model\Session; use Magento\Framework\App\Http\Context as HttpContext; +use Magento\Framework\Exception\LocalizedException; use Magento\Framework\Exception\NoSuchEntityException; +use Magento\Framework\Pricing\PriceCurrencyInterface; use Magento\Framework\UrlInterface; use Magento\Framework\View\Element\Template; use Magento\Sales\Model\Order; @@ -63,6 +68,16 @@ class Script extends Template */ protected $httpContext; + /** + * @var Data + */ + protected $taxHelper; + + /** + * @var PriceCurrencyInterface + */ + protected $priceCurrency; + /** * Script constructor. * @@ -72,6 +87,8 @@ class Script extends Template * @param CustomerSession $customerSession * @param Registry $registry * @param HttpContext $httpContext + * @param Data $taxHelper + * @param PriceCurrencyInterface $priceCurrency * @param array $data */ public function __construct( @@ -81,6 +98,8 @@ public function __construct( CustomerSession $customerSession, Registry $registry, HttpContext $httpContext, + Data $taxHelper, + PriceCurrencyInterface $priceCurrency, array $data = [] ) { $this->helperEmailMarketing = $helperEmailMarketing; @@ -88,6 +107,9 @@ public function __construct( $this->customerSession = $customerSession; $this->registry = $registry; $this->httpContext = $httpContext; + $this->taxHelper = $taxHelper; + $this->priceCurrency = $priceCurrency; + parent::__construct($context, $data); } @@ -141,33 +163,37 @@ public function getCurrencyCode() /** * @return array + * @throws LocalizedException * @throws NoSuchEntityException - * @throws \Magento\Framework\Exception\LocalizedException */ public function getCustomerData() { - $isLoggedIn = $this->httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH); + $isLoggedIn = $this->httpContext->getValue(CustomerContext::CONTEXT_AUTH); if (!$isLoggedIn) { $shippingAddress = $this->checkoutSession->getQuote()->getShippingAddress(); - $data = [ - 'email' => $shippingAddress->getData('email') === null ? '' : $shippingAddress->getData('email'), - 'firstname' => $shippingAddress->getData('firstname') === null ? '' : $shippingAddress->getData('firstname'), - 'lastname' => $shippingAddress->getData('lastname') === null ? '' : $shippingAddress->getData('lastname') + $data = [ + 'email' => $shippingAddress->getData('email') === null ? '' : $shippingAddress->getData('email'), + 'firstname' => $shippingAddress->getData('firstname') === null ? + '' : $shippingAddress->getData('firstname'), + 'lastname' => $shippingAddress->getData('lastname') === null ? + '' : $shippingAddress->getData('lastname') ]; + return $data; } else { $customer = $this->customerSession->create()->getCustomer(); - $data = [ - 'email' => $customer->getData('email') === null ? '' : $customer->getData('email'), + $data = [ + 'email' => $customer->getData('email') === null ? '' : $customer->getData('email'), 'firstname' => $customer->getData('firstname') === null ? '' : $customer->getData('firstname'), - 'lastname' => $customer->getData('lastname') === null ? '' : $customer->getData('lastname') + 'lastname' => $customer->getData('lastname') === null ? '' : $customer->getData('lastname') ]; + return $data; } } /** - * @return array|false + * @return array|bool * @throws NoSuchEntityException */ public function productAbandoned() @@ -181,7 +207,8 @@ public function productAbandoned() 'collections' => [], 'id' => $product->getId(), 'image' => $imageUrl, - 'price' => $product->getFinalPrice(), + 'price' => $this->getPrice($product), + 'priceTax' => $this->getPrice($product, true), 'productType' => $product->getTypeId(), 'tags' => [], 'title' => $product->getName(), @@ -192,4 +219,23 @@ public function productAbandoned() return false; } + + /** + * @param Product $product + * @param bool $includeTax + * + * @return float + */ + public function getPrice($product, $includeTax = false) + { + $price = number_format($this->priceCurrency->convert($product->getFinalPrice()), 2); + + if ($includeTax) { + $price = number_format($this->priceCurrency->convert( + $this->taxHelper->getTaxPrice($product, $product->getFinalPrice(), true) + ), 2); + } + + return $price; + } } diff --git a/Controller/Adminhtml/Smtp/Sync/AbstractEstimate.php b/Controller/Adminhtml/Smtp/Sync/AbstractEstimate.php deleted file mode 100644 index 2842130..0000000 --- a/Controller/Adminhtml/Smtp/Sync/AbstractEstimate.php +++ /dev/null @@ -1,149 +0,0 @@ -emailMarketing = $emailMarketing; - - parent::__construct($context); - } - - /** - * @return ResponseInterface|ResultInterface - */ - public function execute() - { - try { - - if (!$this->emailMarketing->getAppID() || !$this->emailMarketing->getSecretKey()) { - throw new LocalizedException(__('App ID or Secret Key is empty')); - } - - $daysRange = $this->getRequest()->getParam('days_range'); - $from = $this->getRequest()->getParam('from'); - $to = $this->getRequest()->getParam('to'); - $collection = $this->prepareCollection(); - - if ($this->emailMarketing->isOnlyNotSync()) { - $collection->addFieldToFilter('mp_smtp_email_marketing_synced', 0); - } - - $storeId = $this->getRequest()->getParam('storeId'); - $websiteId = $this->getRequest()->getParam('websiteId'); - - if ($storeId) { - $collection->addFieldToFilter($this->storeIdField, $storeId); - } - - if ($websiteId) { - $collection->addFieldToFilter($this->websiteIdField, $websiteId); - } - - if (!$collection instanceof SubscriberCollection && $query = $this->emailMarketing->queryExpr( - $daysRange, - $from, - $to, - $collection instanceof Collection ? 'e' : 'main_table' - ) - ) { - $collection->getSelect()->where($query); - } - - $ids = $collection->getAllIds(); - $result['ids'] = $ids; - $result['total'] = count($ids); - - if ($result['total'] === 0) { - $result['message'] = $this->getZeroMessage(); - } - - $result['status'] = true; - - } catch (Exception $e) { - $result = [ - 'status' => false, - 'message' => $e->getMessage() - ]; - } - - return $this->getResponse()->representJson(EmailMarketing::jsonEncode($result)); - } - - /** - * @return AbstractCollection - */ - abstract public function prepareCollection(); - - /** - * @return Phrase - */ - abstract public function getZeroMessage(); -} diff --git a/Controller/Adminhtml/Smtp/Sync/Customer.php b/Controller/Adminhtml/Smtp/Sync/Customer.php deleted file mode 100644 index d368fb3..0000000 --- a/Controller/Adminhtml/Smtp/Sync/Customer.php +++ /dev/null @@ -1,140 +0,0 @@ -helperEmailMarketing = $helperEmailMarketing; - $this->customerCollectionFactory = $customerCollectionFactory; - parent::__construct($context); - } - - /** - * @return ResponseInterface|ResultInterface - */ - public function execute() - { - $daysRange = $this->getRequest()->getParam('days_range'); - $from = $this->getRequest()->getParam('from'); - $to = $this->getRequest()->getParam('to'); - $result = []; - - try { - $attribute = $this->helperEmailMarketing->getSyncedAttribute(); - $customerCollection = $this->customerCollectionFactory->create(); - $ids = $this->getRequest()->getParam('ids'); - $subscriberTable = $customerCollection->getTable('newsletter_subscriber'); - $customerCollection->getSelect()->columns( - [ - 'subscriber_status' => new Zend_Db_Expr( - '(SELECT `s`.`subscriber_status` FROM `' . $subscriberTable . '` as `s` WHERE `s`.`customer_id` = `e`.`entity_id` LIMIT 1)' - ) - ] - ); - - $customers = $customerCollection->addFieldToFilter('entity_id', ['in' => $ids]); - - if ($this->helperEmailMarketing->isOnlyNotSync()) { - $customers->addFieldToFilter('mp_smtp_email_marketing_synced', 0); - } - - if ($query = $this->helperEmailMarketing->queryExpr($daysRange, $from, $to, 'e')) { - $customerCollection->getSelect()->where($query); - } - - $data = []; - $attributeData = []; - $idUpdate = []; - - foreach ($customers as $customer) { - $data[] = $this->helperEmailMarketing->getCustomerData($customer, false, true); - $attributeData[] = [ - 'attribute_id' => $attribute->getId(), - 'entity_id' => $customer->getId(), - 'value' => 1 - ]; - $idUpdate[] = $customer->getId(); - } - - $result['status'] = true; - $result['total'] = count($ids); - $response = $this->helperEmailMarketing->syncCustomers($data); - $result['log'] = $response; - - if (isset($response['success'])) { - $this->helperEmailMarketing->updateData( - $customers->getConnection(), - $idUpdate, - $customers->getMainTable() - ); - } - - } catch (Exception $e) { - $result['status'] = false; - $result['message'] = $e->getMessage(); - } - - return $this->getResponse()->representJson(EmailMarketing::jsonEncode($result)); - } -} diff --git a/Controller/Adminhtml/Smtp/Sync/Estimate.php b/Controller/Adminhtml/Smtp/Sync/Estimate.php new file mode 100644 index 0000000..8f4ac72 --- /dev/null +++ b/Controller/Adminhtml/Smtp/Sync/Estimate.php @@ -0,0 +1,241 @@ +emailMarketing = $emailMarketing; + $this->customerCollectionFactory = $customerCollectionFactory; + $this->orderCollectionFactory = $orderCollectionFactory; + $this->subscriberCollectionFactory = $subscriberCollectionFactory; + $this->helperData = $helperData; + + parent::__construct($context); + } + + /** + * @return ResponseInterface|ResultInterface + */ + public function execute() + { + try { + + if (!$this->emailMarketing->getAppID() || !$this->emailMarketing->getSecretKey()) { + throw new LocalizedException(__('App ID or Secret Key is empty')); + } + + $daysRange = $this->getRequest()->getParam('daysRange'); + $from = $this->getRequest()->getParam('from'); + $to = $this->getRequest()->getParam('to'); + $type = $this->getRequest()->getParam('type'); + $syncOptions = $this->getRequest()->getParam('syncOptions'); + $collection = $this->prepareCollection($type); + + if ($syncOptions === SyncOptions::NOT_SYNC) { + if ($this->helperData->versionCompare('2.4.0')) { + $collection->getSelect()->where('mp_smtp_email_marketing_synced = ?', 0); + } else { + $collection->addFieldToFilter('mp_smtp_email_marketing_synced', 0); + } + } + + $storeId = $this->getRequest()->getParam('storeId'); + $websiteId = $this->getRequest()->getParam('websiteId'); + + if ($storeId) { + $collection->addFieldToFilter($this->storeIdField, $storeId); + } + + if ($websiteId) { + $collection->addFieldToFilter($this->websiteIdField, $websiteId); + } + + if (!$collection instanceof SubscriberCollection && $daysRange !== 'lifetime' + && $query = $this->emailMarketing->queryExpr( + $daysRange, + $from, + $to, + $collection instanceof Collection ? 'e' : 'main_table' + ) + ) { + $collection->getSelect()->where($query); + } + + $ids = $collection->getAllIds(); + $result['ids'] = $ids; + $result['total'] = count($ids); + + if ($result['total'] === 0) { + $result['message'] = $this->getZeroMessage($type); + } + + $result['status'] = true; + } catch (Exception $e) { + $result = [ + 'status' => false, + 'message' => $e->getMessage() + ]; + } + + return $this->getResponse()->representJson(EmailMarketing::jsonEncode($result)); + } + + /** + * @param int $type + * + * @return bool|Collection|SubscriberCollection|OrderCollection + */ + public function prepareCollection($type) + { + switch ($type) { + case SyncType::CUSTOMERS: + return $this->customerCollectionFactory->create(); + case SyncType::ORDERS: + $orderCollection = $this->orderCollectionFactory->create(); + $storeTable = $orderCollection->getTable('store'); + $this->websiteIdField = 'store_table.website_id'; + $this->storeIdField = 'main_table.store_id'; + $orderCollection->getSelect()->join( + ['store_table' => $storeTable], + 'main_table.store_id = store_table.store_id', + [ + $this->websiteIdField + ] + ); + + return $orderCollection; + case SyncType::SUBSCRIBERS: + $collection = $this->subscriberCollectionFactory->create(); + + if ($this->emailMarketing->getSubscriberConfig() === Newsletter::SUBSCRIBED) { + $collection->addFieldToFilter('subscriber_status', ['eq' => Subscriber::STATUS_SUBSCRIBED]); + } + + return $collection; + default: + return false; + } + } + + /** + * @param int $type + * + * @return Phrase|string + */ + public function getZeroMessage($type) + { + switch ($type) { + case SyncType::CUSTOMERS: + return __('No customers to synchronize.'); + case SyncType::ORDERS: + return __('No Orders to synchronize.'); + case SyncType::SUBSCRIBERS: + return __('No subscriber to synchronize.'); + default: + return ''; + } + } +} diff --git a/Controller/Adminhtml/Smtp/Sync/EstimateCustomer.php b/Controller/Adminhtml/Smtp/Sync/EstimateCustomer.php deleted file mode 100644 index bf867ea..0000000 --- a/Controller/Adminhtml/Smtp/Sync/EstimateCustomer.php +++ /dev/null @@ -1,75 +0,0 @@ -customerCollectionFactory = $customerCollectionFactory; - - parent::__construct($context, $emailMarketing); - } - - /** - * @return Collection|AbstractDb|AbstractCollection - */ - public function prepareCollection() - { - return $this->customerCollectionFactory->create(); - } - - /** - * @return Phrase - */ - public function getZeroMessage() - { - return __('No customers to synchronize.'); - } -} diff --git a/Controller/Adminhtml/Smtp/Sync/EstimateOrder.php b/Controller/Adminhtml/Smtp/Sync/EstimateOrder.php deleted file mode 100644 index 22dc80a..0000000 --- a/Controller/Adminhtml/Smtp/Sync/EstimateOrder.php +++ /dev/null @@ -1,87 +0,0 @@ -orderCollectionFactory = $orderCollectionFactory; - $this->emailMarketing = $emailMarketing; - - parent::__construct($context, $emailMarketing); - } - - /** - * @return AbstractCollection|Collection - */ - public function prepareCollection() - { - $orderCollection = $this->orderCollectionFactory->create(); - $storeTable = $orderCollection->getTable('store'); - $this->websiteIdField = 'store_table.website_id'; - $this->storeIdField = 'main_table.store_id'; - $orderCollection->getSelect()->join( - ['store_table' => $storeTable], - 'main_table.store_id = store_table.store_id', - [ - $this->websiteIdField - ] - ); - - return $orderCollection; - } - - /** - * @return Phrase - */ - public function getZeroMessage() - { - return __('No Orders to synchronize.'); - } -} diff --git a/Controller/Adminhtml/Smtp/Sync/EstimateSubscriber.php b/Controller/Adminhtml/Smtp/Sync/EstimateSubscriber.php deleted file mode 100755 index 52e0b5b..0000000 --- a/Controller/Adminhtml/Smtp/Sync/EstimateSubscriber.php +++ /dev/null @@ -1,82 +0,0 @@ -subscriberCollectionFactory = $subscriberCollectionFactory; - - parent::__construct($context, $emailMarketing); - } - - /** - * @return AbstractCollection|Collection - */ - public function prepareCollection() - { - $collection = $this->subscriberCollectionFactory->create(); - - if ($this->emailMarketing->getSubscriberConfig() === Newsletter::SUBSCRIBED) { - $collection->addFieldToFilter('subscriber_status', ['eq' => Subscriber::STATUS_SUBSCRIBED]); - } - - return $collection; - } - - /** - * @return Phrase - */ - public function getZeroMessage() - { - return __('No subscriber to synchronize.'); - } -} diff --git a/Controller/Adminhtml/Smtp/Sync/Order.php b/Controller/Adminhtml/Smtp/Sync/Order.php deleted file mode 100644 index fba362d..0000000 --- a/Controller/Adminhtml/Smtp/Sync/Order.php +++ /dev/null @@ -1,132 +0,0 @@ -helperEmailMarketing = $helperEmailMarketing; - $this->customerFactory = $customerFactory; - $this->orderCollectionFactory = $orderCollectionFactory; - parent::__construct($context); - } - - /** - * @return ResponseInterface|ResultInterface - */ - public function execute() - { - $daysRange = $this->getRequest()->getParam('days_range'); - $from = $this->getRequest()->getParam('from'); - $to = $this->getRequest()->getParam('to'); - $result = []; - - try { - $orderCollection = $this->orderCollectionFactory->create(); - $ids = $this->getRequest()->getParam('ids'); - $orders = $orderCollection->addFieldToFilter('entity_id', ['in' => $ids]); - - if ($this->helperEmailMarketing->isOnlyNotSync()) { - $orderCollection->addFieldToFilter('mp_smtp_email_marketing_synced', 0); - } - - if ($query = $this->helperEmailMarketing->queryExpr($daysRange, $from, $to)) { - $orderCollection->getSelect()->where($query); - } - - $data = []; - $idUpdate = []; - - foreach ($orders as $order) { - $data[] = $this->helperEmailMarketing->getOrderData($order); - $idUpdate[] = $order->getId(); - } - - $result['status'] = true; - $result['total'] = count($ids); - $response = $this->helperEmailMarketing->syncOrders($data); - $result['log'] = $response; - - if (isset($response['success'])) { - $this->helperEmailMarketing->updateData( - $orders->getConnection(), - $idUpdate, - $orders->getMainTable() - ); - } - - } catch (Exception $e) { - $result['status'] = false; - $result['message'] = $e->getMessage(); - } - - return $this->getResponse()->representJson(EmailMarketing::jsonEncode($result)); - } -} diff --git a/Controller/Adminhtml/Smtp/Sync/Subscriber.php b/Controller/Adminhtml/Smtp/Sync/Subscriber.php deleted file mode 100755 index 3dbb0dc..0000000 --- a/Controller/Adminhtml/Smtp/Sync/Subscriber.php +++ /dev/null @@ -1,189 +0,0 @@ -helperEmailMarketing = $helperEmailMarketing; - $this->subscriberCollectionFactory = $subscriberCollectionFactory; - $this->customerCollectionFactory = $customerCollectionFactory; - $this->_localeDate = $localeDate; - parent::__construct($context); - } - - /** - * @return ResponseInterface|ResultInterface - */ - public function execute() - { - $result = []; - - try { - $collection = $this->subscriberCollectionFactory->create(); - $ids = $this->getRequest()->getParam('ids'); - - if ($this->helperEmailMarketing->getSubscriberConfig() === Newsletter::SUBSCRIBED) { - $collection->addFieldToFilter('subscriber_status', ['eq' => ModelSubscriber::STATUS_SUBSCRIBED]); - } - - $data = []; - $subscribers = $collection->addFieldToFilter('subscriber_id', ['in' => $ids]); - - if ($this->helperEmailMarketing->isOnlyNotSync()) { - $subscribers->addFieldToFilter('mp_smtp_email_marketing_synced', 0); - } - - $idUpdate = []; - - foreach ($subscribers as $subscriber) { - switch ($subscriber->getSubscriberStatus()) { - case ModelSubscriber::STATUS_SUBSCRIBED: - $status = self::SUB; - break; - case ModelSubscriber::STATUS_UNSUBSCRIBED: - $status = self::UNSUB; - break; - default: - $status = self::NOTSUB; - break; - } - - if ($subscriber->getCustomerId()) { - $customerCollection = $this->customerCollectionFactory->create(); - $customerCollection->addFieldToFilter('entity_id', ['eq' => $subscriber->getCustomerId()]); - - foreach ($customerCollection as $customer) { - $customerData = $this->helperEmailMarketing->getCustomerData( - $customer, - false, - true - ); - $customerData['status'] = $status; - $customerData['tags'] = 'newsletter'; - $customerData['isSubscriber'] = true; - $data[] = $customerData; - } - - } else { - $data[] = [ - 'id' => (int) $subscriber->getId(), - 'email' => $subscriber->getSubscriberEmail(), - 'status' => $status, - 'source' => 'Magento', - 'tags' => 'newsletter', - 'isSubscriber' => true, - 'timezone' => $this->_localeDate->getConfigTimezone( - ScopeInterface::SCOPE_STORE, - $subscriber->getStoreId() - ) - ]; - - $idUpdate[] = $subscriber->getId(); - } - } - - $result['status'] = true; - $result['total'] = count($ids); - $response = $this->helperEmailMarketing->syncCustomers($data); - $result['log'] = $response; - - if (isset($response['success'])) { - $this->helperEmailMarketing->updateData( - $subscribers->getConnection(), - $idUpdate, - $subscribers->getMainTable(), - true - ); - } - - } catch (Exception $e) { - $result['status'] = false; - $result['message'] = $e->getMessage(); - } - - return $this->getResponse()->representJson(EmailMarketing::jsonEncode($result)); - } -} diff --git a/Controller/Adminhtml/Smtp/Sync/Sync.php b/Controller/Adminhtml/Smtp/Sync/Sync.php new file mode 100644 index 0000000..ed1df32 --- /dev/null +++ b/Controller/Adminhtml/Smtp/Sync/Sync.php @@ -0,0 +1,379 @@ +helperEmailMarketing = $helperEmailMarketing; + $this->customerCollectionFactory = $customerCollectionFactory; + $this->orderCollectionFactory = $orderCollectionFactory; + $this->subscriberCollectionFactory = $subscriberCollectionFactory; + $this->localeDate = $localeDate; + $this->helperData = $helperData; + + parent::__construct($context); + } + + /** + * @return ResponseInterface|ResultInterface + */ + public function execute() + { + $daysRange = $this->getRequest()->getParam('daysRange'); + $from = $this->getRequest()->getParam('from'); + $to = $this->getRequest()->getParam('to'); + $type = $this->getRequest()->getParam('type'); + $syncOptions = $this->getRequest()->getParam('syncOptions'); + $result = []; + + switch ($type) { + case SyncType::CUSTOMERS: + $result = $this->syncCustomers($syncOptions, $daysRange, $from, $to); + break; + case SyncType::ORDERS: + $result = $this->syncOrders($syncOptions, $daysRange, $from, $to); + break; + case SyncType::SUBSCRIBERS: + $result = $this->syncSubscribers($syncOptions); + break; + } + + return $this->getResponse()->representJson(EmailMarketing::jsonEncode($result)); + } + + /** + * @param string $syncOptions + * @param string $daysRange + * @param string $from + * @param string $to + * + * @return mixed + */ + public function syncCustomers($syncOptions, $daysRange, $from, $to) + { + try { + $attribute = $this->helperEmailMarketing->getSyncedAttribute(); + $customerCollection = $this->customerCollectionFactory->create(); + $ids = $this->getRequest()->getParam('ids'); + $subscriberTable = $customerCollection->getTable('newsletter_subscriber'); + $customerCollection->getSelect()->columns( + [ + 'subscriber_status' => new Zend_Db_Expr( + '(SELECT `s`.`subscriber_status` FROM `' + . $subscriberTable . '` as `s` WHERE `s`.`customer_id` = `e`.`entity_id` LIMIT 1)' + ) + ] + ); + + $customers = $customerCollection->addFieldToFilter('entity_id', ['in' => $ids]); + + if ($syncOptions === SyncOptions::NOT_SYNC) { + if ($this->helperData->versionCompare('2.4.0')) { + $customers->getSelect()->where('mp_smtp_email_marketing_synced = ?', 0); + } else { + $customers->addFieldToFilter('mp_smtp_email_marketing_synced', 0); + } + } + + if ($daysRange !== 'lifetime' + && $query = $this->helperEmailMarketing->queryExpr($daysRange, $from, $to, 'e')) { + $customers->getSelect()->where($query); + } + + $data = []; + $attributeData = []; + $idUpdate = []; + + foreach ($customers as $customer) { + $data[] = $this->helperEmailMarketing->getCustomerData($customer, false, true); + $attributeData[] = [ + 'attribute_id' => $attribute->getId(), + 'entity_id' => $customer->getId(), + 'value' => 1 + ]; + $idUpdate[] = $customer->getId(); + } + + $result['status'] = true; + $result['total'] = count($ids); + $response = $this->helperEmailMarketing->syncCustomers($data); + $result['log'] = $response; + + if (isset($response['success'])) { + $this->helperEmailMarketing->updateData( + $customers->getConnection(), + $idUpdate, + $customers->getMainTable() + ); + } + + } catch (Exception $e) { + $result['status'] = false; + $result['message'] = $e->getMessage(); + } + + return $result; + } + + /** + * @param string $syncOptions + * @param string $daysRange + * @param string $from + * @param string $to + * + * @return mixed + */ + public function syncOrders($syncOptions, $daysRange, $from, $to) + { + try { + $orderCollection = $this->orderCollectionFactory->create(); + $ids = $this->getRequest()->getParam('ids'); + $orders = $orderCollection->addFieldToFilter('entity_id', ['in' => $ids]); + + if ($syncOptions === SyncOptions::NOT_SYNC) { + if ($this->helperData->versionCompare('2.4.0')) { + $orders->getSelect()->where('mp_smtp_email_marketing_synced = ?', 0); + } else { + $orders->addFieldToFilter('mp_smtp_email_marketing_synced', 0); + } + } + + if ($daysRange !== 'lifetime' && $query = $this->helperEmailMarketing->queryExpr($daysRange, $from, $to)) { + $orders->getSelect()->where($query); + } + + $data = []; + $idUpdate = []; + + foreach ($orders as $order) { + $data[] = $this->helperEmailMarketing->getOrderData($order); + $idUpdate[] = $order->getId(); + } + + $result['status'] = true; + $result['total'] = count($ids); + $response = $this->helperEmailMarketing->syncOrders($data); + $result['log'] = $response; + + if (isset($response['success'])) { + $this->helperEmailMarketing->updateData( + $orders->getConnection(), + $idUpdate, + $orders->getMainTable() + ); + } + + } catch (Exception $e) { + $result['status'] = false; + $result['message'] = $e->getMessage(); + } + + return $result; + } + + /** + * @param string $syncOptions + * + * @return mixed + */ + public function syncSubscribers($syncOptions) + { + try { + $collection = $this->subscriberCollectionFactory->create(); + $ids = $this->getRequest()->getParam('ids'); + + if ($this->helperEmailMarketing->getSubscriberConfig() === Newsletter::SUBSCRIBED) { + $collection->addFieldToFilter('subscriber_status', ['eq' => ModelSubscriber::STATUS_SUBSCRIBED]); + } + + $data = []; + $subscribers = $collection->addFieldToFilter('subscriber_id', ['in' => $ids]); + + if ($syncOptions === SyncOptions::NOT_SYNC) { + if ($this->helperData->versionCompare('2.4.0')) { + $subscribers->getSelect()->where('mp_smtp_email_marketing_synced = ?', 0); + } else { + $subscribers->addFieldToFilter('mp_smtp_email_marketing_synced', 0); + } + } + + $idUpdate = []; + + foreach ($subscribers as $subscriber) { + switch ($subscriber->getSubscriberStatus()) { + case ModelSubscriber::STATUS_SUBSCRIBED: + $status = self::SUB; + break; + case ModelSubscriber::STATUS_UNSUBSCRIBED: + $status = self::UNSUB; + break; + default: + $status = self::NOTSUB; + break; + } + + $updatedAt = $this->helperEmailMarketing->formatDate($subscriber->getChangeStatusAt()); + + if ($subscriber->getCustomerId()) { + $customerCollection = $this->customerCollectionFactory->create(); + $customerCollection->addFieldToFilter('entity_id', ['eq' => $subscriber->getCustomerId()]); + + foreach ($customerCollection as $customer) { + $customerData = $this->helperEmailMarketing->getCustomerData( + $customer, + false, + true + ); + $customerData['status'] = $status; + $customerData['tags'] = 'newsletter'; + $customerData['isSubscriber'] = true; + $customerData['isSubscriber'] = true; + $customerData['is_utc'] = true; + $customerData['updated_at'] = $updatedAt; + $data[] = $customerData; + } + + } else { + $data[] = [ + 'id' => (int) $subscriber->getId(), + 'email' => $subscriber->getSubscriberEmail(), + 'status' => $status, + 'source' => 'Magento', + 'tags' => 'newsletter', + 'isSubscriber' => true, + 'timezone' => $this->localeDate->getConfigTimezone( + ScopeInterface::SCOPE_STORE, + $subscriber->getStoreId() + ), + 'is_utc' => true, + 'updated_at' => $updatedAt + ]; + + $idUpdate[] = $subscriber->getId(); + } + } + + $result['status'] = true; + $result['total'] = count($ids); + $response = $this->helperEmailMarketing->syncCustomers($data); + $result['log'] = $response; + + if (isset($response['success'])) { + $this->helperEmailMarketing->updateData( + $subscribers->getConnection(), + $idUpdate, + $subscribers->getMainTable(), + true + ); + } + + } catch (Exception $e) { + $result['status'] = false; + $result['message'] = $e->getMessage(); + } + + return $result; + } +} diff --git a/Controller/Proxy/Index.php b/Controller/Proxy/Index.php new file mode 100644 index 0000000..22ab1e5 --- /dev/null +++ b/Controller/Proxy/Index.php @@ -0,0 +1,72 @@ +helperEmailMarketing = $helperEmailMarketing; + + parent::__construct($context); + } + + /** + * @return ResponseInterface|ResultInterface + */ + public function execute() + { + try { + $params = $this->getRequest()->getParams(); + $response = $this->helperEmailMarketing->sendRequestProxy($params); + } catch (Exception $e) { + $response = []; + } + + return $this->getResponse()->representJson(Data::jsonEncode($response)); + } +} diff --git a/Helper/EmailMarketing.php b/Helper/EmailMarketing.php index 45e6f20..f4809ab 100644 --- a/Helper/EmailMarketing.php +++ b/Helper/EmailMarketing.php @@ -65,6 +65,7 @@ use Magento\Shipping\Helper\Data as ShippingHelper; use Magento\Store\Model\ScopeInterface; use Magento\Store\Model\StoreManagerInterface; +use Mageplaza\Smtp\Model\ResourceModel\AbandonedCart\Grid\Collection; use Psr\Log\LoggerInterface; use Magento\Sales\Model\Order\Config as OrderConfig; use Magento\Store\Model\Information; @@ -73,7 +74,6 @@ use Zend_Db_Expr; use Magento\Framework\App\ResourceConnection; use Mageplaza\Smtp\Model\Config\Source\DaysRange; -use Mageplaza\Smtp\Model\Config\Source\SyncOptions; use Zend_Db_Select_Exception; use Magento\Directory\Model\Region; @@ -84,18 +84,19 @@ class EmailMarketing extends Data { const IS_SYNCED_ATTRIBUTE = 'mp_smtp_is_synced'; - const API_URL = 'https://app.avada.io'; - const APP_URL = self::API_URL . '/app/api/v1/connects'; - const CHECKOUT_URL = self::API_URL . '/app/api/v1/checkouts'; - const CUSTOMER_URL = self::API_URL . '/app/api/v1/customers'; - const ORDER_URL = self::API_URL . '/app/api/v1/orders'; - const ORDER_COMPLETE_URL = self::API_URL . '/app/api/v1/orders/complete'; - const INVOICE_URL = self::API_URL . '/app/api/v1/orders/invoice'; - const SHIPMENT_URL = self::API_URL . '/app/api/v1/orders/ship'; - const CREDITMEMO_URL = self::API_URL . '/app/api/v1/orders/refund'; - const DELETE_URL = self::API_URL . '/app/api/v1/checkouts?id='; - const SYNC_CUSTOMER_URL = self::API_URL . '/app/api/v1/customers/bulk'; - const SYNC_ORDER_URL = self::API_URL . '/app/api/v1/orders/bulk'; + const API_URL = 'https://app.avada.io'; + const APP_URL = self::API_URL . '/app/api/v1/connects'; + const CHECKOUT_URL = self::API_URL . '/app/api/v1/checkouts'; + const CUSTOMER_URL = self::API_URL . '/app/api/v1/customers'; + const ORDER_URL = self::API_URL . '/app/api/v1/orders'; + const ORDER_COMPLETE_URL = self::API_URL . '/app/api/v1/orders/complete'; + const INVOICE_URL = self::API_URL . '/app/api/v1/orders/invoice'; + const SHIPMENT_URL = self::API_URL . '/app/api/v1/orders/ship'; + const CREDITMEMO_URL = self::API_URL . '/app/api/v1/orders/refund'; + const DELETE_URL = self::API_URL . '/app/api/v1/checkouts?id='; + const SYNC_CUSTOMER_URL = self::API_URL . '/app/api/v1/customers/bulk'; + const SYNC_ORDER_URL = self::API_URL . '/app/api/v1/orders/bulk'; + const PROXY_URL = self::API_URL . '/app/api/v1/proxy/'; /** * @var UrlInterface @@ -253,6 +254,11 @@ class EmailMarketing extends Data */ protected $region; + /** + * @var Collection + */ + protected $abandonedCartCollection; + /** * EmailMarketing constructor. * @@ -284,6 +290,7 @@ class EmailMarketing extends Data * @param CountryFactory $countryFactory * @param ResourceConnection $resourceConnection * @param Region $region + * @param Collection $abandonedCartCollection */ public function __construct( Context $context, @@ -313,10 +320,9 @@ public function __construct( StoreFactory $storeFactory, CountryFactory $countryFactory, ResourceConnection $resourceConnection, - Region $region + Region $region, + Collection $abandonedCartCollection ) { - parent::__construct($context, $objectManager, $storeManager); - $this->frontendUrl = $frontendUrl; $this->escaper = $escaper; $this->productConfig = $catalogConfiguration; @@ -342,6 +348,9 @@ public function __construct( $this->countryFactory = $countryFactory; $this->resourceConnection = $resourceConnection; $this->region = $region; + $this->abandonedCartCollection = $abandonedCartCollection; + + parent::__construct($context, $objectManager, $storeManager); } /** @@ -505,13 +514,15 @@ public function getQuoteUpdatedAt($quoteId) } /** - * @param string $date + * @param string|null $date * * @return string - * @throws Exception + * @throws LocalizedException */ public function formatDate($date) { + $date = $this->_localeDate->convertConfigTimeToUtc($date); + return $this->_localeDate->formatDateTime( $date, IntlDateFormatter::MEDIUM, @@ -537,6 +548,7 @@ public function getOrderData($object) 'shipping_price' => $object->getShippingAmount(), 'currency' => $object->getBaseCurrencyCode(), 'order_currency' => $object->getOrderCurrencyCode(), + 'is_utc' => true, 'created_at' => $this->formatDate($object->getCreatedAt()), 'updated_at' => $this->formatDate($object->getUpdatedAt()), 'timezone' => $this->_localeDate->getConfigTimezone( @@ -627,7 +639,6 @@ public function getOrderData($object) if ($isShipment || $isCreditmemo || $isInvoice) { $data['line_items'] = $this->getShipmentOrCreditmemoItems($object); - } else { $data['line_items'] = $this->getCartItems($object); } @@ -654,7 +665,7 @@ public function getOrderData($object) } /** - * @param $object + * @param Object $object * * @return array */ @@ -688,17 +699,18 @@ public function getDataAddress($object) */ public function sendOrderRequest($object, $url = '') { + $data = $this->getOrderData($object); + if (!$url) { - $url = self::ORDER_URL; + $data['checkout_id'] = $object->getQuoteId(); + $url = self::ORDER_URL; } - - $data = $this->getOrderData($object); $this->storeId = $object->getStoreId(); $this->sendRequest($data, $url); } /** - * @param $data + * @param array $data * * @return mixed * @throws LocalizedException @@ -766,11 +778,12 @@ public function getACEData($quote, array $address = null, $isOsc = false) 'line_items' => $this->getCartItems($quote), 'currency' => $quote->getStoreCurrencyCode(), 'presentment_currency' => $quote->getStoreCurrencyCode(), + 'is_utc' => true, 'created_at' => $createdAt, 'updated_at' => $updatedAt, 'abandoned_checkout_url' => $this->getRecoveryUrl($quote), - 'subtotal_price' => (float)$quote->getBaseSubtotal(), - 'total_price' => (float)$quote->getData('base_grand_total'), + 'subtotal_price' => (float) $quote->getBaseSubtotal(), + 'total_price' => (float) $quote->getData('base_grand_total'), 'total_tax' => !$quote->isVirtual() ? $quote->getShippingAddress()->getBaseTaxAmount() : 0, 'customer_locale' => null, 'shipping_address' => $this->getShippingAddress($quote, $address), @@ -820,7 +833,7 @@ public function getBillingAddress(Quote $quote, $address = null, $isOsc = false) * * @return array */ - public function getAddress(Quote $quote, Address $addressObject, array $addr = null, string $field) + public function getAddress(Quote $quote, Address $addressObject, $addr, $field) { $result = []; @@ -850,9 +863,10 @@ public function getAddress(Quote $quote, Address $addressObject, array $addr = n } /** - * @param Shipment | Creditmemo $object + * @param Shipment|Creditmemo $object * * @return array + * @throws LocalizedException * @throws NoSuchEntityException */ public function getShipmentOrCreditmemoItems($object) @@ -869,7 +883,11 @@ public function getShipmentOrCreditmemoItems($object) 'product_id' => $orderItem->getProductId(), 'sku' => $orderItem->getSku(), 'quantity' => $item->getQty(), - 'price' => (float) $item->getBasePrice() + 'price' => (float) $item->getBasePrice(), + 'is_utc' => true, + 'created_at' => $this->formatDate($product->getCreatedAt()), + 'updated_at' => $this->formatDate($product->getUpdatedAt()), + 'categories' => $product->getCategoryIds() ]; continue; @@ -895,7 +913,11 @@ public function getShipmentOrCreditmemoItems($object) 'sku' => $item->getSku(), 'product_id' => $item->getProductId(), 'image' => $this->getProductImage($product), - 'frontend_link' => $product->getProductUrl() + 'frontend_link' => $product->getProductUrl(), + 'is_utc' => true, + 'created_at' => $this->formatDate($item->getProduct()->getCreatedAt()), + 'updated_at' => $this->formatDate($item->getProduct()->getUpdatedAt()), + 'categories' => $item->getProduct()->getCategoryIds() ]; if ($productType === 'bundle') { @@ -915,7 +937,7 @@ public function getShipmentOrCreditmemoItems($object) } /** - * @param $item + * @param Item $item * * @return string */ @@ -927,8 +949,8 @@ public function getOptionsWithName($item) } /** - * @param $item - * @param $options + * @param Item $item + * @param array $options * * @return string */ @@ -943,7 +965,7 @@ public function formatOptions($item, $options) } /** - * @param $orderItem + * @param Item $orderItem * * @return string */ @@ -980,6 +1002,7 @@ public function getProductFromItem($item) * @param Quote|Shipment|Creditmemo|Order $object * * @return array + * @throws LocalizedException * @throws NoSuchEntityException */ public function getCartItems($object) @@ -1010,8 +1033,10 @@ public function getCartItems($object) } } - $products = $this->productRepository->get($item->getData('sku')); - if(is_object($products->getCustomAttribute($this->getDefineVendor()))){ + $sku = $isBundle ? $item->getProduct()->getSku() : $item->getData('sku'); + $products = $this->productRepository->get($sku); + + if (is_object($products->getCustomAttribute($this->getDefineVendor()))) { $vendorValue = $products->getAttributeText($this->getDefineVendor()); } else { $vendorValue = ''; @@ -1028,17 +1053,20 @@ public function getCartItems($object) 'product_id' => $item->getProductId(), 'image' => $this->getProductImage($product), 'frontend_link' => $product->getProductUrl() ?: '#', - 'vendor' => $vendorValue + 'vendor' => $vendorValue, + 'is_utc' => true, + 'created_at' => $this->formatDate($item->getProduct()->getCreatedAt()), + 'updated_at' => $this->formatDate($item->getProduct()->getUpdatedAt()), + 'categories' => $item->getProduct()->getCategoryIds() ]; if ($isQuote) { - $itemRequest['line_price'] = (float)$item->getBaseRowTotal(); + $itemRequest['line_price'] = (float) $item->getBaseRowTotal(); } if ($item->getHasChildren()) { $children = $isQuote ? $item->getChildren() : $item->getChildrenItems(); foreach ($children as $child) { - $product = $this->getProductFromItem($child); if ($hasVariant) { $itemRequest['variant_title'] = $child->getName(); @@ -1055,7 +1083,11 @@ public function getCartItems($object) 'product_id' => $child->getProductId(), 'sku' => $child->getSku(), 'quantity' => (int) ($isQuote ? $child->getQty() : $child->getQtyOrdered()), - 'price' => (float) $child->getBasePrice() + 'price' => (float) $child->getBasePrice(), + 'is_utc' => true, + 'created_at' => $this->formatDate($product->getCreatedAt()), + 'updated_at' => $this->formatDate($product->getUpdatedAt()), + 'categories' => $product->getCategoryIds() ]; } } @@ -1182,6 +1214,7 @@ public function sendRequestWithoutWaitResponse($data, $url = '', $appID = '', $s $this->_curl->setOption(CURLOPT_TIMEOUT_MS, 500); $this->_curl->post($this->url, $body); } catch (Exception $e) { + $this->_logger->critical($e->getMessage()); // Ignore exception timeout } } @@ -1241,12 +1274,18 @@ public function getTags(Customer $customer) * @param Customer $customer * @param bool $isLoadSubscriber * @param bool $isUpdateOrder + * @param null $address * * @return array * @throws LocalizedException + * @throws NoSuchEntityException */ - public function getCustomerData(Customer $customer, $isLoadSubscriber = false, $isUpdateOrder = false) - { + public function getCustomerData( + Customer $customer, + $isLoadSubscriber = false, + $isUpdateOrder = false, + $address = null + ) { if ($isLoadSubscriber) { $subscriber = $this->_subscriberFactory->create()->loadByEmail($customer->getEmail()); @@ -1261,7 +1300,7 @@ public function getCustomerData(Customer $customer, $isLoadSubscriber = false, $ 'email' => $customer->getEmail(), 'firstName' => $customer->getFirstname(), 'lastName' => $customer->getLastname(), - 'phoneNumber' => '', + 'phoneNumber' => $address ? $address->getTelephone() : '', 'description' => '', 'isSubscriber' => $isSubscriber, 'tags' => $this->getTags($customer), @@ -1270,19 +1309,23 @@ public function getCustomerData(Customer $customer, $isLoadSubscriber = false, $ ScopeInterface::SCOPE_STORE, $customer->getStoreId() ), - 'customer_type' => 'new_customer' + 'customer_type' => 'new_customer', + 'dob' => $customer->getDob() ? $this->formatDate($customer->getDob()) : '', + 'is_utc' => true, + 'created_at' => $this->formatDate($customer->getCreatedAt()), + 'updated_at' => $this->formatDate($customer->getUpdatedAt()) ]; $defaultBillingAddress = $customer->getDefaultBillingAddress(); if ($defaultBillingAddress) { $data['countryCode'] = $defaultBillingAddress->getCountryId(); - $country = $this->countryFactory->create()->loadByCode($data['countryCode']); - $data['country'] = $country->getName(); - $data['city'] = $defaultBillingAddress->getCity(); - $renderer = $this->_addressConfig->getFormatByCode(ElementFactory::OUTPUT_FORMAT_ONELINE) + $country = $this->countryFactory->create()->loadByCode($data['countryCode']); + $data['country'] = $country->getName(); + $data['city'] = $defaultBillingAddress->getCity(); + $renderer = $this->_addressConfig->getFormatByCode(ElementFactory::OUTPUT_FORMAT_ONELINE) ->getRenderer(); - $data['address'] = $renderer->renderArray($defaultBillingAddress->getData()); - $data['phoneNumber'] = $defaultBillingAddress->getTelephone(); + $data['address'] = $renderer->renderArray($defaultBillingAddress->getData()); + $data['phoneNumber'] = $defaultBillingAddress->getTelephone(); } if ($isUpdateOrder) { @@ -1304,7 +1347,7 @@ public function getCustomerData(Customer $customer, $isLoadSubscriber = false, $ } /** - * @param $customerId + * @param int $customerId * * @return mixed */ @@ -1333,7 +1376,7 @@ public function getLifetimeSales($customerId) } /** - * @param $connection + * @param AdapterInterface $connection * * @return string|null */ @@ -1406,6 +1449,7 @@ public function getBaseCurrencyByWebsiteId($websiteId) * * @return mixed * @throws LocalizedException + * @throws Zend_Db_Select_Exception */ public function testConnection($appID, $secretKey) { @@ -1418,6 +1462,7 @@ public function testConnection($appID, $secretKey) /** * @return array + * @throws Zend_Db_Select_Exception */ public function getStoreInformation() { @@ -1444,7 +1489,9 @@ public function getStoreInformation() 'address1' => $this->getConfigData(Information::XML_PATH_STORE_INFO_STREET_LINE1, $scope, $scopeCode), 'address2' => $this->getConfigData(Information::XML_PATH_STORE_INFO_STREET_LINE2, $scope, $scopeCode), 'email' => $this->getConfigData('trans_email/ident_general/email'), - 'contact_count' => $this->getContactCount() ?: 0 + 'contact_count' => $this->getContactCount() ?: 0, + 'order_count' => $this->orderCollection->getSize(), + 'ace_count' => $this->abandonedCartCollection->getSize() ]; if ($info['countryCode']) { @@ -1623,20 +1670,42 @@ public function updateData($connection, $ids, $table, $subscriber = false) } /** + * @param string|null $storeId + * * @return mixed */ - public function isOnlyNotSync() + public function isTracking($storeId = null) { - return $this->getEmailMarketingConfig('synchronization/sync_options') === SyncOptions::NOT_SYNC; + return $this->getEmailMarketingConfig('is_tracking', $storeId); } /** - * @param string|null $storeId + * @param array $data * * @return mixed + * @throws LocalizedException + * @throws NoSuchEntityException */ - public function isTracking($storeId = null) + public function sendRequestProxy($data) { - return $this->getEmailMarketingConfig('is_tracking', $storeId); + $url = self::PROXY_URL; + if (isset($data['path'])) { + $url = self::PROXY_URL . $data['path']; + } + + $this->initCurl(); + + if ($this->_request->getMethod() === 'POST') { + $body = $this->setHeaders($data, $url); + $this->_curl->post($this->url, $body); + } else { + $this->_curl->get($this->url); + } + + $body = $this->_curl->getBody(); + $bodyData = self::jsonDecode($body); + $this->_curl = ''; + + return $bodyData; } } diff --git a/Model/Config/Source/DaysRange.php b/Model/Config/Source/DaysRange.php index 2d89b94..6024090 100755 --- a/Model/Config/Source/DaysRange.php +++ b/Model/Config/Source/DaysRange.php @@ -52,11 +52,11 @@ public function toOptionArray() public function toArray() { return [ - '30' => __('30'), - '60' => __('60'), + 'lifetime' => __('Lifetime'), '90' => __('90'), - '365' => __('365'), - self::CUSTOM => __('Custom') + '365' => __('1 Year'), + '730' => __('2 Years'), + self::CUSTOM => __('Choose Date Range') ]; } } diff --git a/Model/Config/Source/SyncOptions.php b/Model/Config/Source/SyncOptions.php index 9dcc668..0b8b670 100755 --- a/Model/Config/Source/SyncOptions.php +++ b/Model/Config/Source/SyncOptions.php @@ -46,7 +46,7 @@ public function toOptionArray() ], [ 'value' => self::NOT_SYNC, - 'label' => __('New Object') + 'label' => __('New Object Only') ] ]; diff --git a/Model/Config/Source/SyncType.php b/Model/Config/Source/SyncType.php new file mode 100755 index 0000000..57cd7d7 --- /dev/null +++ b/Model/Config/Source/SyncType.php @@ -0,0 +1,65 @@ + self::CUSTOMERS, + 'label' => __('Customers') + ], + [ + 'value' => self::ORDERS, + 'label' => __('Orders') + ], + [ + 'value' => self::SUBSCRIBERS, + 'label' => __('Subscribers') + ], + [ + 'value' => self::ALL, + 'label' => __('Every Thing') + ] + ]; + + return $options; + } +} diff --git a/Observer/Customer/CustomerSaveCommitAfter.php b/Observer/Customer/CustomerSaveCommitAfter.php index fa052e7..34f289c 100644 --- a/Observer/Customer/CustomerSaveCommitAfter.php +++ b/Observer/Customer/CustomerSaveCommitAfter.php @@ -63,8 +63,8 @@ public function __construct( ResourceCustomer $resourceCustomer ) { $this->helperEmailMarketing = $helperEmailMarketing; - $this->logger = $logger; - $this->resourceCustomer = $resourceCustomer; + $this->logger = $logger; + $this->resourceCustomer = $resourceCustomer; } /** @@ -82,19 +82,19 @@ public function execute(Observer $observer) ) { try { $isLoadSubscriber = !$customer->getIsNewRecord(); - $data = $this->helperEmailMarketing->getCustomerData($customer, $isLoadSubscriber); + $data = $this->helperEmailMarketing->getCustomerData($customer, $isLoadSubscriber); if ($customer->getIsNewRecord()) { $result = $this->helperEmailMarketing->syncCustomer($data); if (!empty($result['success'])) { $this->helperEmailMarketing->setIsSyncedCustomer(true); - $table = $this->resourceCustomer->getTable('customer_entity_int'); + $table = $this->resourceCustomer->getTable('customer_entity_int'); $connection = $this->resourceCustomer->getConnection(); - $attribute = $this->helperEmailMarketing->getSyncedAttribute(); - $data = [ + $attribute = $this->helperEmailMarketing->getSyncedAttribute(); + $data = [ 'attribute_id' => $attribute->getId(), - 'entity_id' => $customer->getId(), - 'value' => 1 + 'entity_id' => $customer->getId(), + 'value' => 1 ]; $connection->insert($table, $data); } diff --git a/Observer/Customer/SaveAddress.php b/Observer/Customer/SaveAddress.php index dd91b23..70011a0 100644 --- a/Observer/Customer/SaveAddress.php +++ b/Observer/Customer/SaveAddress.php @@ -54,7 +54,7 @@ public function __construct( LoggerInterface $logger ) { $this->helperEmailMarketing = $helperEmailMarketing; - $this->logger = $logger; + $this->logger = $logger; } /** @@ -65,7 +65,7 @@ public function execute(Observer $observer) /** * @var Customer $customer */ - $address = $observer->getEvent()->getDataObject(); + $address = $observer->getEvent()->getDataObject(); $customer = $address->getCustomer(); if ($address->getIsDefaultBilling() && $customer->getMpSmtpIsSynced() && @@ -74,7 +74,7 @@ public function execute(Observer $observer) $this->helperEmailMarketing->getAppID() ) { try { - $data = $this->helperEmailMarketing->getCustomerData($customer, true); + $data = $this->helperEmailMarketing->getCustomerData($customer, true, false, $address); $this->helperEmailMarketing->syncCustomer($data, false); } catch (Exception $e) { diff --git a/Observer/Customer/SubscriberSaveCommitAfter.php b/Observer/Customer/SubscriberSaveCommitAfter.php index 3fb90bf..6abe794 100644 --- a/Observer/Customer/SubscriberSaveCommitAfter.php +++ b/Observer/Customer/SubscriberSaveCommitAfter.php @@ -65,8 +65,8 @@ public function __construct( LoggerInterface $logger ) { $this->helperEmailMarketing = $helperEmailMarketing; - $this->logger = $logger; - $this->customerRepository = $customerRepository; + $this->logger = $logger; + $this->customerRepository = $customerRepository; } /** @@ -84,14 +84,16 @@ public function execute(Observer $observer) try { $data = [ - 'email' => $subscriber->getSubscriberEmail(), - 'firstName' => '', - 'lastName' => '', - 'phoneNumber' => '', - 'description' => '', - 'source' => 'Magento', - 'isSubscriber' => $subscriber->getSubscriberStatus() === Subscriber::STATUS_SUBSCRIBED, - 'customer_type' => 'new_subscriber' + 'email' => $subscriber->getSubscriberEmail(), + 'firstName' => '', + 'lastName' => '', + 'phoneNumber' => '', + 'description' => '', + 'source' => 'Magento', + 'isSubscriber' => $subscriber->getSubscriberStatus() === Subscriber::STATUS_SUBSCRIBED, + 'customer_type' => 'new_subscriber', + 'is_utc' => true, + 'updated_at' => $this->helperEmailMarketing->formatDate($subscriber->getChangeStatusAt()) ]; /** @@ -100,7 +102,7 @@ public function execute(Observer $observer) $customer = $this->getCustomerByEmail($subscriber->getSubscriberEmail()); if ($customer && $customer->getId()) { $data['firstName'] = $customer->getFirstname(); - $data['lastName'] = $customer->getLastname(); + $data['lastName'] = $customer->getLastname(); } $this->helperEmailMarketing->syncCustomer($data, false); @@ -112,6 +114,7 @@ public function execute(Observer $observer) /** * @param string $email + * * @return CustomerInterface|string */ public function getCustomerByEmail($email) diff --git a/Observer/Order/CreditmemoCreate.php b/Observer/Order/CreditmemoCreate.php index 55f4e69..1fa68af 100644 --- a/Observer/Order/CreditmemoCreate.php +++ b/Observer/Order/CreditmemoCreate.php @@ -55,7 +55,7 @@ public function __construct( LoggerInterface $logger ) { $this->helperEmailMarketing = $helperEmailMarketing; - $this->logger = $logger; + $this->logger = $logger; } /** diff --git a/Observer/Order/InvoiceCommitAfter.php b/Observer/Order/InvoiceCommitAfter.php index adabffd..40ffa8d 100644 --- a/Observer/Order/InvoiceCommitAfter.php +++ b/Observer/Order/InvoiceCommitAfter.php @@ -23,6 +23,8 @@ use Magento\Framework\Event\Observer; use Magento\Framework\Event\ObserverInterface; +use Magento\Framework\Exception\LocalizedException; +use Magento\Framework\Exception\NoSuchEntityException; use Magento\Sales\Model\Order\Invoice; use Mageplaza\Smtp\Helper\EmailMarketing; @@ -50,6 +52,9 @@ public function __construct( /** * @param Observer $observer + * + * @throws LocalizedException + * @throws NoSuchEntityException */ public function execute(Observer $observer) { @@ -63,7 +68,7 @@ public function execute(Observer $observer) if ($invoice->getId() && $invoice->getCreatedAt() == $invoice->getUpdatedAt()) { $this->helperEmailMarketing->sendOrderRequest($invoice, EmailMarketing::INVOICE_URL); } - $this->helperEmailMarketing->updateCustomer($invoice->getOrder()->getCustomerId()); + $this->helperEmailMarketing->updateCustomer($invoice->getOrder()->getCustomerId()); } } } diff --git a/Observer/Order/OrderComplete.php b/Observer/Order/OrderComplete.php index 6877b40..57624a9 100644 --- a/Observer/Order/OrderComplete.php +++ b/Observer/Order/OrderComplete.php @@ -63,8 +63,8 @@ public function __construct( ResourceOrder $resourceOrder ) { $this->helperEmailMarketing = $helperEmailMarketing; - $this->logger = $logger; - $this->resourceOrder = $resourceOrder; + $this->logger = $logger; + $this->resourceOrder = $resourceOrder; } /** @@ -79,14 +79,17 @@ public function execute(Observer $observer) ) { try { /* @var Order $order */ - $order = $observer->getEvent()->getOrder(); + $order = $observer->getEvent()->getOrder(); $isSynced = $order->getData('mp_smtp_email_marketing_synced'); if (!in_array($order->getState(), [Order::STATE_NEW, Order::STATE_COMPLETE], true)) { $data = [ - 'id' => $order->getId(), - 'status' => $order->getStatus(), - 'state' => $order->getState(), - 'email' => $order->getCustomerEmail() + 'id' => $order->getId(), + 'status' => $order->getStatus(), + 'state' => $order->getState(), + 'email' => $order->getCustomerEmail(), + 'is_utc' => true, + 'created_at' => $this->helperEmailMarketing->formatDate($order->getCreatedAt()), + 'updated_at' => $this->helperEmailMarketing->formatDate($order->getUpdatedAt()) ]; $this->helperEmailMarketing->updateOrderStatusRequest($data); } diff --git a/Observer/Order/OrderCreate.php b/Observer/Order/OrderCreate.php index a26ede3..e4479bd 100644 --- a/Observer/Order/OrderCreate.php +++ b/Observer/Order/OrderCreate.php @@ -55,7 +55,7 @@ public function __construct( LoggerInterface $logger ) { $this->helperEmailMarketing = $helperEmailMarketing; - $this->logger = $logger; + $this->logger = $logger; } /** diff --git a/Observer/Order/ShipmentCreate.php b/Observer/Order/ShipmentCreate.php index d86a455..070c2bf 100644 --- a/Observer/Order/ShipmentCreate.php +++ b/Observer/Order/ShipmentCreate.php @@ -55,7 +55,7 @@ public function __construct( LoggerInterface $logger ) { $this->helperEmailMarketing = $helperEmailMarketing; - $this->logger = $logger; + $this->logger = $logger; } /** diff --git a/Plugin/DefaultAttributes.php b/Plugin/DefaultAttributes.php index 1272512..95ddaee 100644 --- a/Plugin/DefaultAttributes.php +++ b/Plugin/DefaultAttributes.php @@ -21,7 +21,6 @@ namespace Mageplaza\Smtp\Plugin; -use Magento\Framework\Exception\MailException; use Magento\Eav\Model\Entity\AbstractEntity; /** @@ -32,7 +31,8 @@ class DefaultAttributes { /** * @param AbstractEntity $subject - * @param $result + * @param array $result + * * @return array */ public function afterGetDefaultAttributes(AbstractEntity $subject, $result) diff --git a/composer.json b/composer.json index 4d56702..d65819f 100644 --- a/composer.json +++ b/composer.json @@ -5,7 +5,7 @@ "mageplaza/module-core": "^1.4.11" }, "type": "magento2-module", - "version": "1.9.3", + "version": "1.10.0", "license": "proprietary", "authors": [ { diff --git a/etc/adminhtml/system.xml b/etc/adminhtml/system.xml index 59a08c7..32368e4 100644 --- a/etc/adminhtml/system.xml +++ b/etc/adminhtml/system.xml @@ -185,15 +185,19 @@ + + + Mageplaza\Smtp\Model\Config\Source\SyncType + Mageplaza\Smtp\Model\Config\Source\SyncOptions - If "New Object" is selected, only sync objects that have never been synced to Marketing Automation App + If "New Object Only" is selected, only sync objects that have never been synced to Marketing Automation App - - + + Mageplaza\Smtp\Model\Config\Source\DaysRange - If "Custom" is selected, all the records will be sync if the "Created From - To" is empty. + If "Choose Date Range" is selected, all the records will be sync if the "Created From - To" is empty. @@ -202,23 +206,11 @@ custom - - - Synchronize Customers - adminhtml/smtp_sync/customer - Mageplaza\Smtp\Block\Adminhtml\System\Config\SyncCustomer - - - - Synchronize Orders - adminhtml/smtp_sync/order - Mageplaza\Smtp\Block\Adminhtml\System\Config\SyncOrder - - + - Synchronize Subscribers - adminhtml/smtp_sync/subscriber - Mageplaza\Smtp\Block\Adminhtml\System\Config\SyncSubscriber + Synchronize Now + adminhtml/smtp_sync/sync + Mageplaza\Smtp\Block\Adminhtml\System\Config\Sync 1 diff --git a/etc/config.xml b/etc/config.xml index 0884738..27e2c2d 100644 --- a/etc/config.xml +++ b/etc/config.xml @@ -37,7 +37,9 @@ 0 0 + 1 all + lifetime diff --git a/i18n/en_US.csv b/i18n/en_US.csv index 870bce8..87bd20d 100644 --- a/i18n/en_US.csv +++ b/i18n/en_US.csv @@ -199,3 +199,5 @@ ID,ID Recipient,Recipient Cc,Cc Bcc,Bcc +"Order synchronization has been completed.","Order synchronization has been completed." +"Subscriber synchronization has been completed.","Subscriber synchronization has been completed." diff --git a/view/adminhtml/templates/system/config/sync-template.phtml b/view/adminhtml/templates/system/config/sync-template.phtml index ccb0a91..42c54f2 100644 --- a/view/adminhtml/templates/system/config/sync-template.phtml +++ b/view/adminhtml/templates/system/config/sync-template.phtml @@ -19,13 +19,19 @@ * @license https://www.mageplaza.com/LICENSE.txt */ -/** @var \Mageplaza\Smtp\Block\Adminhtml\System\Config\SyncCustomer $block */ +use Mageplaza\Smtp\Block\Adminhtml\System\Config\Sync; +use Mageplaza\Smtp\Helper\Data; + +/** @var Sync $block */ ?>