diff --git a/CHANGELOG.md b/CHANGELOG.md index 0f17876bc..7ea2ac227 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,7 +1,27 @@ # Change Log -## [1.1.14](https://github.com/mailchimp/mc-magento/tree/1.1.14) (2019-01-16) +## [1.1.15](https://github.com/mailchimp/mc-magento/tree/1.1.15) (2019-02-18) + +[Full Changelog](https://github.com/mailchimp/mc-magento/compare/1.1.14...1.1.15) + +**Implemented enhancements:** + +- Catch exception if mandrill api is not available [\#859](https://github.com/mailchimp/mc-magento/issues/859) +- Add subscription option on order success page [\#770](https://github.com/mailchimp/mc-magento/issues/770) +**Fixed bugs:** + +- Subscribers status doesn't change to subscribed if double opt-in is activated using Magento email through Mandrill [\#874](https://github.com/mailchimp/mc-magento/issues/874) +- Multiple confirmation email from Mailchimp after group subscription [\#873](https://github.com/mailchimp/mc-magento/issues/873) +- Undefined variable: acl [\#871](https://github.com/mailchimp/mc-magento/issues/871) +- Spelling error in order status sent to mailchimp [\#868](https://github.com/mailchimp/mc-magento/issues/868) +- Subscription fails when one store view is disabled with the API key in blank [\#867](https://github.com/mailchimp/mc-magento/issues/867) +- The program fails when set up the extension in one store view and disable another store view leaving the API key in blank [\#863](https://github.com/mailchimp/mc-magento/issues/863) +- Avoid real time calls to Mailchimp API in case it's down [\#862](https://github.com/mailchimp/mc-magento/issues/862) +- If connection ping fails for one store it cancels the entire process [\#846](https://github.com/mailchimp/mc-magento/issues/846) +- 1.1.12 "Display on order grid" also hides Ebizmarts\_MailChimp\_Block\_Adminhtml\_Sales\_Order\_View\_Info\_Monkey [\#826](https://github.com/mailchimp/mc-magento/issues/826) + +## [1.1.14](https://github.com/mailchimp/mc-magento/tree/1.1.14) (2019-01-16) [Full Changelog](https://github.com/mailchimp/mc-magento/compare/1.1.13...1.1.14) **Implemented enhancements:** @@ -11,6 +31,8 @@ **Fixed bugs:** +- Flag parent as modified when child product is modified [\#848](https://github.com/mailchimp/mc-magento/issues/848) +- Change modified abandoned carts sending method from DELETE -\> POST to PATCH [\#836](https://github.com/mailchimp/mc-magento/issues/836) - Orders belonging to deleted stores do not show correct syncing status under "synced to MailChimp" column [\#840](https://github.com/mailchimp/mc-magento/issues/840) ## [1.1.13](https://github.com/mailchimp/mc-magento/tree/1.1.13) (2018-12-11) @@ -18,6 +40,8 @@ **Implemented enhancements:** +- Add option to send unresized product images to Mailchimp [\#834](https://github.com/mailchimp/mc-magento/issues/834) +- Optimize deletion of processed webhooks [\#832](https://github.com/mailchimp/mc-magento/issues/832) - Send subscription confirmation email via Magento [\#793](https://github.com/mailchimp/mc-magento/issues/793) - Order confirmation email is bypassing Aschroder\_SMTPPro [\#673](https://github.com/mailchimp/mc-magento/issues/673) - Add support for List Groups [\#514](https://github.com/mailchimp/mc-magento/issues/514) @@ -452,4 +476,4 @@ ## [1.0.0](https://github.com/mailchimp/mc-magento/tree/1.0.0) (2016-06-06) -\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)* \ No newline at end of file +\* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)* diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Customer/Edit/Tab/Mailchimp.php b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Customer/Edit/Tab/Mailchimp.php new file mode 100644 index 000000000..e15943121 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Block/Adminhtml/Customer/Edit/Tab/Mailchimp.php @@ -0,0 +1,99 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 6/10/16 12:38 AM + * @file: Grid.php + */ +class Ebizmarts_MailChimp_Block_Adminhtml_Customer_Edit_Tab_Mailchimp extends Mage_Adminhtml_Block_Widget_Grid +{ + + protected $_lists = array(); + protected $_info = array(); + protected $_myLists = array(); + protected $_generalList = array(); + protected $_form; + protected $_api; + protected $_customer; + /** + * @var Ebizmarts_MailChimp_Helper_Data + */ + protected $helper; + protected $storeId; + + public function __construct() + { + parent::__construct(); + $this->setTemplate('ebizmarts/mailchimp/customer/tab/mailchimp.phtml'); + $this->helper = $this->makeHelper(); + $customerId = (int) $this->getRequest()->getParam('id'); + if ($customerId) { + $this->_customer = $this->getCustomerModel()->load($customerId); + $this->storeId = $this->getCustomer()->getStoreId(); + } + } + + public function getInterest() + { + $customer = $this->getCustomer(); + $subscriber = $this->getSubscriberModel(); + $subscriber->loadByEmail($customer->getEmail()); + $subscriberId = $subscriber->getSubscriberId(); + $customerId = $customer->getId(); + $storeId = $this->getStoreId(); + $interest = $this->helper->getInterestGroups($customerId, $subscriberId, $storeId); + + return $interest; + } + + /** + * @return Mage_Newsletter_Model_Subscriber + */ + protected function getSubscriberModel() + { + return Mage::getModel('newsletter/subscriber'); + } + + /** + * @return Ebizmarts_MailChimp_Helper_Data + */ + protected function makeHelper() + { + return Mage::helper('mailchimp'); + } + + /** + * @return false|Mage_Core_Model_Abstract + */ + protected function getCustomerModel() + { + return Mage::getModel('customer/customer'); + } + + /** + * @return Mage_Core_Model_Abstract + */ + protected function getCustomer() + { + return $this->_customer; + } + + /** + * If customer was created in admin panel use the store view selected for MailChimp. + * + * @return mixed + */ + protected function getStoreId() + { + $storeId = $this->storeId; + if (!$storeId) { + $storeId = $this->_customer->getMailchimpStoreView(); + } + return $storeId; + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Checkout/Subscribe.php b/app/code/community/Ebizmarts/MailChimp/Block/Checkout/Subscribe.php index 96e519d1f..e3fc73cde 100644 --- a/app/code/community/Ebizmarts/MailChimp/Block/Checkout/Subscribe.php +++ b/app/code/community/Ebizmarts/MailChimp/Block/Checkout/Subscribe.php @@ -17,6 +17,9 @@ class Ebizmarts_MailChimp_Block_Checkout_Subscribe extends Mage_Core_Block_Templ protected $_generalList = array(); protected $_form; protected $_api; + /** + * @var Ebizmarts_MailChimp_Helper_Data + */ protected $helper; protected $storeId; @@ -116,8 +119,6 @@ public function getGeneralList() $helper = $this->helper; $listId = $helper->getGeneralList($storeId); - //@Todo add support for intetest groups - return $listId; } } diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Checkout/Success/Groups.php b/app/code/community/Ebizmarts/MailChimp/Block/Checkout/Success/Groups.php new file mode 100644 index 000000000..3053d292e --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Block/Checkout/Success/Groups.php @@ -0,0 +1,87 @@ + + * @license http://opensource.org/licenses/osl-3.0.php + */ +class Ebizmarts_MailChimp_Block_Checkout_Success_Groups extends Mage_Core_Block_Template +{ + protected $_currentIntesrest; + /** + * @var Ebizmarts_MailChimp_Helper_Data + */ + protected $helper; + protected $storeId; + + public function __construct() + { + parent::__construct(); + $this->helper = Mage::helper('mailchimp'); + $this->storeId = Mage::app()->getStore()->getId(); + } + + public function getFormUrl() + { + return $this->getSuccessInterestUrl(); + } + + public function getSuccessInterestUrl() + { + $url = 'mailchimp/group/index'; + return Mage::app()->getStore()->getUrl($url); + } + + public function getInterest() + { + $subscriber = $this->getSubscriberModel(); + $order = $this->getSessionLastRealOrder(); + $subscriber->loadByEmail($order->getCustomerEmail()); + $subscriberId = $subscriber->getSubscriberId(); + $customerId = $order->getCustomerId(); + $helper = $this->getMailChimpHelper(); + $interest = $helper->getInterestGroups($customerId, $subscriberId, $order->getStoreId()); + return $interest; + } + + public function getMessageBefore() + { + $storeId = $this->storeId; + $message = $this->getMailChimpHelper()->getCheckoutSuccessHtmlBefore($storeId); + return $message; + } + + public function getMessageAfter() + { + $storeId = $this->storeId; + $message = $this->getMailChimpHelper()->getCheckoutSuccessHtmlAfter($storeId); + return $message; + } + + /** + * @return false|Mage_Core_Model_Abstract + */ + protected function getSubscriberModel() + { + return Mage::getModel('newsletter/subscriber'); + } + + /** + * @return mixed + */ + protected function getSessionLastRealOrder() + { + return Mage::getSingleton('checkout/session')->getLastRealOrder(); + } + + /** + * @return Ebizmarts_MailChimp_Helper_Data|Mage_Core_Helper_Abstract + */ + protected function getMailChimpHelper() + { + return $this->helper; + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Customer/Newsletter/Index.php b/app/code/community/Ebizmarts/MailChimp/Block/Customer/Newsletter/Index.php new file mode 100644 index 000000000..3f3462005 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Block/Customer/Newsletter/Index.php @@ -0,0 +1,86 @@ + + * @license http://opensource.org/licenses/osl-3.0.php + */ +class Ebizmarts_MailChimp_Block_Customer_Newsletter_Index extends Mage_Customer_Block_Newsletter +{ + + protected $_lists = array(); + protected $_info = array(); + protected $_myLists = array(); + protected $_generalList = array(); + protected $_form; + protected $_api; + protected $_template = "ebizmarts/mailchimp/customer/newsletter/index.phtml"; + /** + * @var Ebizmarts_MailChimp_Helper_Data + */ + protected $helper; + protected $storeId; + + public function __construct() + { + $this->setTemplate('ebizmarts/mailchimp/customer/newsletter/index.phtml'); + $this->helper = Mage::helper('mailchimp'); + $this->storeId = Mage::app()->getStore()->getId(); + } + + public function getInterest() + { + $subscriber = $this->getSubscriberModel(); + $subscriber->loadByEmail($this->_getEmail()); + $helper = $this->getMailChimpHelper(); + $customerSession = $this->getCustomerSession(); + if (!$helper->isAdmin() && $customerSession->isLoggedIn()) { + $customer = $customerSession->getCustomer(); + $customerId = $customer->getId(); + $storeId = ($subscriber->getStoreId()) ? $subscriber->getStoreId() : $customer->getStoreId(); + } else { + $customerId = null; + $storeId = $subscriber->getStoreId(); + } + $interest = $helper->getInterestGroups($customerId, $subscriber->getSubscriberId(), $storeId); + return $interest; + } + + /** + * Retrieve email from Customer object in session + * + * @return string Email address + */ + protected function _getEmail() + { + return $this->helper('customer')->getCustomer()->getEmail(); + } + + /** + * @return Ebizmarts_MailChimp_Helper_Data + */ + protected function getMailChimpHelper() + { + return $this->helper; + } + + /** + * @return Mage_Customer_Model_Session + */ + protected function getCustomerSession() + { + return Mage::getSingleton('customer/session'); + } + + /** + * @return Mage_Newsletter_Model_Subscriber + */ + protected function getSubscriberModel() + { + return Mage::getModel('newsletter/subscriber'); + } + +} diff --git a/app/code/community/Ebizmarts/MailChimp/Block/Group/Type.php b/app/code/community/Ebizmarts/MailChimp/Block/Group/Type.php new file mode 100644 index 000000000..bfdf6600f --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Block/Group/Type.php @@ -0,0 +1,32 @@ + + * @license http://opensource.org/licenses/osl-3.0.php + */ +class Ebizmarts_MailChimp_Block_Group_Type extends Mage_Core_Block_Template +{ + protected $_currentInterest; + + public function __construct(array $args = array()) + { + if (isset($args['interests'])) { + $this->_currentInterest = $interests = $args['interests']; + $type = $interests['interest']['type']; + $this->setTemplate("ebizmarts/mailchimp/group/type/$type.phtml"); + } + parent::__construct($args); + } + + /** + * @return mixed + */ + protected function getCurrentInterest() + { + return $this->_currentInterest; + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php index e8517f541..c41dcbe14 100755 --- a/app/code/community/Ebizmarts/MailChimp/Helper/Data.php +++ b/app/code/community/Ebizmarts/MailChimp/Helper/Data.php @@ -12,6 +12,10 @@ */ class Ebizmarts_MailChimp_Helper_Data extends Mage_Core_Helper_Abstract { + const DEFAULT_SIZE = '0'; + const SMALL_SIZE = '1'; + const THUMBNAIL_SIZE = '2'; + const ORIGINAL_SIZE = '3'; /** * All MailChimp available language codes @@ -275,6 +279,16 @@ public function isMailChimpEnabled($scopeId, $scope = null) return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE, $scopeId, $scope); } + /** + * + * @param $scopeId + * @return bool | returns true if useMagentoEmails is enabled + */ + public function isUseMagentoEmailsEnabled ($scopeId) + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_MAGENTO_MAIL, $scopeId); + } + /** * Return if module is enabled and list selected for given scope. * @@ -1313,20 +1327,22 @@ public function getImageUrlById($productId, $magentoStoreId) $productModel = $this->getProductModel(); $configImageSize = $this->getImageSize($magentoStoreId); switch ($configImageSize) { - case 0: + case self::DEFAULT_SIZE: $imageSize = Ebizmarts_MailChimp_Model_Config::IMAGE_SIZE_DEFAULT; break; - case 1: + case self::SMALL_SIZE: $imageSize = Ebizmarts_MailChimp_Model_Config::IMAGE_SIZE_SMALL; break; - case 2: + case self::THUMBNAIL_SIZE: $imageSize = Ebizmarts_MailChimp_Model_Config::IMAGE_SIZE_THUMBNAIL; break; + case self::ORIGINAL_SIZE: + $imageSize = Ebizmarts_MailChimp_Model_Config::IMAGE_SIZE_DEFAULT; + break; default: $imageSize = Ebizmarts_MailChimp_Model_Config::IMAGE_SIZE_DEFAULT; break; } - $productImage = $productResourceModel->getAttributeRawValue($productId, $imageSize, $magentoStoreId); $productModel->setData($imageSize, $productImage); @@ -1335,13 +1351,22 @@ public function getImageUrlById($productId, $magentoStoreId) } else { $curStore = $this->getCurrentStoreId(); $this->setCurrentStore($magentoStoreId); - $upperCaseImage = $this->getImageFunctionName($imageSize); - $imageUrl = $productModel->$upperCaseImage(); + if ($configImageSize == self::ORIGINAL_SIZE){ + $imageUrl = $this->getOriginalPath($productImage); + } else { + $imageUrl = $this->getImageUrlForSize($imageSize, $productModel); + } $this->setCurrentStore($curStore); } + return $imageUrl; } + public function getImageUrl($productModel, $imageSize) + { + return (string)$this->_getImageHelper()->init($productModel, $imageSize); + } + /** * Returns imageSize converted to camel case, and concatenates with functionName * @@ -1359,6 +1384,18 @@ public function getImageFunctionName($imageSize) return $functionName; } + /** + * @param $imageSize + * @param $productModel + * @return string + */ + protected function getImageUrlForSize($imageSize, $productModel) + { + $upperCaseImage = (string)$this->getImageFunctionName($imageSize); + $imageUrl = $productModel->$upperCaseImage(); + return $imageUrl; + } + /** * Returns imageSize separated word by word in array * @@ -1472,7 +1509,7 @@ public function getCoreResource() } /** - * @return false|Mage_Core_Model_Abstract + * @return Mage_Core_Model_Website */ protected function getCoreWebsite() { @@ -1547,6 +1584,8 @@ protected function getOrderCollectionByCustomerEmail($subscriberEmail) * Return html code for adding the MailChimp javascript. * * @return string + * @throws Mage_Core_Exception + * @throws Mage_Core_Model_Store_Exception */ public function getMCJs() { @@ -1555,14 +1594,14 @@ public function getMCJs() $storeId = $this->getMageApp()->getStore()->getId(); if ($this->isEcomSyncDataEnabled($storeId)) { $currentUrl = $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_MC_JS_URL, $storeId); + if ($this->areJsUrlAndListScopesEqual($storeId)) { $url = $currentUrl; } - if (!$url) { - $url = $this->getApiStores()->getMCJsUrl($storeId, 'stores'); + if ($url !== null) { + $script = ''; } - $script = ''; } return $script; } @@ -2826,8 +2865,8 @@ public function getSubscriberAmountLimit() public function getStoreLanguageCode($scopeId, $scope = 'stores') { - $isAdmin = Mage::app()->getStore()->isAdmin(); - $userLangCode = Mage::app()->getLocale()->getLocaleCode(); + $isAdmin = $this->isAdmin(); + $userLangCode = Mage::app()->getLocale()->getLocaleCode(); if ($isAdmin || '' == $lang = $this->_lang2MCLanguage($userLangCode)) { // IS Admin OR if users lang is not supported, try store views default locale $userLangCode = $this->getConfigValueForScope(Mage_Core_Model_Locale::XML_PATH_DEFAULT_LOCALE, $scopeId, $scope); @@ -2925,6 +2964,8 @@ protected function isNotDefaultScope($config) } /** + * Returns true if the js URL belongs to the same scope as where the list has been configured. + * * @param $storeId * @return bool */ @@ -3151,4 +3192,282 @@ public function getPromoConfig($scopeId, $scope = null) { return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_SEND_PROMO, $scopeId, $scope); } + + + public function getListInterestCategories($scopeId, $scope = 'stores') + { + $interestGroupsArray = array(); + $api = $this->getApi($scopeId, $scope); + $listId = $this->getGeneralList($scopeId, $scope); + try { + $interestCategories = $api->getLists()->getInterestCategory()->getAll($listId, 'categories'); + foreach ($interestCategories['categories'] as $interestCategory) { + $interestGroupsArray[] = array( + 'id' => $interestCategory['id'], + 'title' => $interestCategory['title'], + 'type' => $interestCategory['type'] + ); + } + } catch (Exception $e) { + $this->logError($e->getMessage()); + } + return $interestGroupsArray; + } + + public function getListInterestGroups($scopeId, $scope = 'stores') + { + $interestGroupsArray = array(); + $api = $this->getApi($scopeId, $scope); + $listId = $this->getGeneralList($scopeId, $scope); + try { + $apiInterestCategory = $api->getLists()->getInterestCategory(); + $interestCategories = $apiInterestCategory->getAll($listId, 'categories'); + foreach ($interestCategories['categories'] as $interestCategory) { + $interestGroups = $apiInterestCategory->getInterests()->getAll($listId, $interestCategory['id']); + $groups = array(); + foreach ($interestGroups['interests'] as $interestGroup) { + $groups[$interestGroup['id']] = $interestGroup['name']; + } + $interestGroupsArray[] = array( + 'id' => $interestCategory['id'], + 'title' => $interestCategory['title'], + 'type' => $interestCategory['type'], + 'groups' => $groups + ); + } + } catch (Exception $e) { + $this->logError($e->getMessage()); + } + return $interestGroupsArray; + } + + public function getLocalInterestCategories($scopeId, $scope = 'stores') + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_INTEREST_CATEGORIES, $scopeId, $scope); + } + + public function getCheckoutSuccessHtmlBefore($scopeId, $scope = 'stores') + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_INTEREST_SUCCESS_BEFORE, $scopeId, $scope); + } + + public function getCheckoutSuccessHtmlAfter($scopeId, $scope = 'stores') + { + return $this->getConfigValueForScope(Ebizmarts_MailChimp_Model_Config::GENERAL_INTEREST_SUCCESS_AFTER, $scopeId, $scope); + } + + /** + * @param $storeId + * @return array + * @throws MailChimp_Error + */ + public function getInterest($storeId) + { + $rc = array(); + $interest = $this->getLocalInterestCategories($storeId); + if ($interest != '') { + $interest = explode(",", $interest); + + } else { + $interest = array(); + } + $api = $this->getApi($storeId); + $listId = $this->getGeneralList($storeId); + try { + $apiInterestCategory = $api->getLists()->getInterestCategory(); + $allInterest = $apiInterestCategory->getAll($listId); + foreach ($allInterest['categories'] as $item) { + if (in_array($item['id'], $interest)) { + $rc[$item['id']]['interest'] = array('id' => $item['id'], 'title' => $item['title'], 'type' => $item['type']); + } + } + $apiInterestCategoryInterest = $apiInterestCategory->getInterests(); + foreach ($interest as $interestId) { + $mailchimpInterest = $apiInterestCategoryInterest->getAll($listId, $interestId); + foreach ($mailchimpInterest['interests'] as $mi) { + $rc[$mi['category_id']]['category'][$mi['display_order']] = array('id' => $mi['id'], 'name' => $mi['name'], 'checked' => false); + } + } + } catch (MailChimp_Error $e) { + $this->logError($e->getFriendlyMessage()); + } + return $rc; + } + + /** + * @param $customerId + * @param $subscriberId + * @param $storeId + * @param null $interest + * @return array|null + * @throws MailChimp_Error + */ + public function getInterestGroups($customerId, $subscriberId, $storeId, $interest = null) + { + if ($this->isSubscriptionEnabled($storeId)) { + if (!$interest) { + $interest = $this->getInterest($storeId); + } + $interestGroup = $this->getInterestGroupModel(); + $interestGroup->getByRelatedIdStoreId($customerId, $subscriberId, $storeId); + if ($interestGroup->getId()) { + $groups = $this->arrayDecode($interestGroup->getGroupdata()); + foreach ($groups as $key => $value) { + if (isset($interest[$key])) { + if (is_array($value)) { + foreach ($value as $groupId) { + foreach ($interest[$key]['category'] as $gkey => $gvalue) { + if ($gvalue['id'] == $groupId) { + $interest[$key]['category'][$gkey]['checked'] = true; + } elseif (!isset($interest[$key]['category'][$gkey]['checked'])) { + $interest[$key]['category'][$gkey]['checked'] = false; + } + } + } + } else { + foreach ($interest[$key]['category'] as $gkey => $gvalue) { + if ($gvalue['id'] == $value) { + $interest[$key]['category'][$gkey]['checked'] = true; + } else { + $interest[$key]['category'][$gkey]['checked'] = false; + } + } + } + } + } + } + return $interest; + } else { + return array(); + } + } + + + /** + * Format array to save in database. + * + * @param $array + * @return string + */ + public function arrayEncode($array) + { + return json_encode($array); + } + + /** + * Set database encoded array to normal array + * + * @param $encodedArray + * @return mixed + */ + public function arrayDecode($encodedArray) + { + return json_decode($encodedArray, true); + } + + /** + * @param $params + * @param $storeId + * @param null $customerId + * @param null $subscriber + * @throws Mage_Core_Model_Store_Exception + */ + public function saveInterestGroupData($params, $storeId, $customerId = null, $subscriber = null) + { + $groups = $this->getInterestGroupsIfAvailable($params); + if (!$customerId) { + $customerSession = $this->getCustomerSession(); + if ($this->isAdmin()) { + $customerId = $params['customer_id']; + } elseif ($customerSession->isLoggedIn()) { + $customerData = $customerSession->getCustomer(); + $customerId = $customerData->getId(); + } + } + $subscriberId = null; + if ($subscriber) { + $subscriberId = $subscriber->getSubscriberId(); + } + $interestGroup = $this->getInterestGroupModel(); + $interestGroup->getByRelatedIdStoreId($customerId, $subscriberId, $storeId); + $origSubscriberId = $interestGroup->getSubscriberId(); + $origCustomerId = $interestGroup->getCustomerId(); + if (!$origSubscriberId || $subscriberId && $origSubscriberId != $subscriberId) { + $interestGroup->setSubscriberId($subscriberId); + } + if (!$origCustomerId || $customerId && $origCustomerId != $customerId) { + $interestGroup->setCustomerId($customerId); + } + if ($groups) { + $encodedGroups = $this->arrayEncode($groups); + $interestGroup->setGroupdata($encodedGroups); + } + //Avoid creating a new entry if no groupData available. (Customer creation) + if ($interestGroup->getGroupdata()) { + if ($storeId) { + $interestGroup->setStoreId($storeId); + } + $interestGroup->setUpdatedAt($this->getCurrentDateTime()); + $interestGroup->save(); + } + } + + /** + * @param $params + * @return mixed + */ + public function getInterestGroupsIfAvailable($params) + { + $groups = null; + if (isset($params['customer']) && isset($params['customer']['interestgroup'])) { + $groups = $params['customer']['interestgroup']; + } elseif (isset($params['group'])) { + $groups = $params['group']; + } + return $groups; + } + + /** + * @return bool + * @throws Mage_Core_Model_Store_Exception + */ + public function isAdmin() + { + return Mage::app()->getStore()->isAdmin(); + } + + /** + * @return Ebizmarts_MailChimp_Model_Interestgroup + */ + protected function getInterestGroupModel() + { + return Mage::getModel('mailchimp/interestgroup'); + } + + /** + * @return Mage_Customer_Model_Session + */ + protected function getCustomerSession() + { + return Mage::getSingleton('customer/session'); + } + + /** + * @return mixed + */ + protected function getCurrentDateTime() + { + return Mage::getModel('core/date')->date('d-m-Y H:i:s'); + } + + /** + * Return original path for the imageURL (not the catched one) + * + * @param $productImage + * @return string + */ + protected function getOriginalPath($productImage) + { + return Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_MEDIA) . 'catalog/product' . $productImage; + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php index 747d53118..c276fe6b2 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Batches.php @@ -197,14 +197,16 @@ public function handleEcommerceBatches() $helper->handleResendDataBefore(); foreach ($stores as $store) { $storeId = $store->getId(); - if(!$this->_ping($storeId)) { - $helper->logError('Could not connect to MailChimp: Make sure the API Key is correct and there is an internet connection'); - return; - } if ($helper->isEcomSyncDataEnabled($storeId)) { - $this->_getResults($storeId); - $this->_sendEcommerceBatch($storeId); + if ($this->_ping($storeId)) { + $this->_getResults($storeId); + $this->_sendEcommerceBatch($storeId); + } else { + $helper->logError('Could not connect to MailChimp: Make sure the API Key is correct and there is an internet connection'); + return; + } } + } $helper->handleResendDataAfter(); diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php old mode 100644 new mode 100755 index ebd770c9a..c92435c4a --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Carts.php @@ -11,14 +11,13 @@ */ class Ebizmarts_MailChimp_Model_Api_Carts { - const BATCH_LIMIT = 100; protected $_firstDate; protected $_counter; protected $_batchId; - protected $_api = null; + protected $_api = null; protected $_token = null; /** @@ -28,6 +27,7 @@ class Ebizmarts_MailChimp_Model_Api_Carts */ public function createBatchJson($mailchimpStoreId, $magentoStoreId) { + /** @var Ebizmarts_MailChimp_Helper_Data $helper */ $helper = $this->getHelper(); $allCarts = array(); if (!$helper->isAbandonedCartEnabled($magentoStoreId)) { @@ -35,10 +35,10 @@ public function createBatchJson($mailchimpStoreId, $magentoStoreId) } $this->_firstDate = $helper->getAbandonedCartFirstDate($magentoStoreId); - $this->_counter = 0; + $this->setCounter(0); $date = $helper->getDateMicrotime(); - $this->_batchId = 'storeid-' . $magentoStoreId . '_' . Ebizmarts_MailChimp_Model_Config::IS_QUOTE . '_' . $date; + $this->setBatchId('storeid-' . $magentoStoreId . '_' . Ebizmarts_MailChimp_Model_Config::IS_QUOTE . '_' . $date); $resendTurn = $helper->getResendTurn($magentoStoreId); if (!$resendTurn) { // get all the carts converted in orders (must be deleted on mailchimp) @@ -56,11 +56,12 @@ public function createBatchJson($mailchimpStoreId, $magentoStoreId) * @param $magentoStoreId * @return array */ - protected function _getConvertedQuotes($mailchimpStoreId, $magentoStoreId) + public function _getConvertedQuotes($mailchimpStoreId, $magentoStoreId) { - $mailchimpTableName = Mage::getSingleton('core/resource')->getTableName('mailchimp/ecommercesyncdata'); + $mailchimpTableName = $this->getMailchimpEcommerceDataTableName(); + $batchId = $this->getBatchId(); $allCarts = array(); - $convertedCarts = Mage::getResourceModel('sales/quote_collection'); + $convertedCarts = $this->getQuoteCollection(); // get only the converted quotes $convertedCarts->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); $convertedCarts->addFieldToFilter('is_active', array('eq' => 0)); @@ -78,26 +79,28 @@ protected function _getConvertedQuotes($mailchimpStoreId, $magentoStoreId) foreach ($convertedCarts as $cart) { $cartId = $cart->getEntityId(); // we need to delete all the carts associated with this email - $allCartsForEmail = $this->_getAllCartsByEmail($cart->getCustomerEmail(), $mailchimpStoreId, $magentoStoreId); + $allCartsForEmail = $this->getAllCartsByEmail($cart->getCustomerEmail(), $mailchimpStoreId, $magentoStoreId); foreach ($allCartsForEmail as $cartForEmail) { $alreadySentCartId = $cartForEmail->getEntityId(); + $counter = $this->getCounter(); if ($alreadySentCartId != $cartId) { - $allCarts[$this->_counter]['method'] = 'DELETE'; - $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $alreadySentCartId; - $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $alreadySentCartId; - $allCarts[$this->_counter]['body'] = ''; + $allCarts[$counter]['method'] = 'DELETE'; + $allCarts[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $alreadySentCartId; + $allCarts[$counter]['operation_id'] = $batchId . '_' . $alreadySentCartId; + $allCarts[$counter]['body'] = ''; $this->_updateSyncData($alreadySentCartId, $mailchimpStoreId, null, null, null, null, 1); - $this->_counter += 1; + $this->setCounter($this->getCounter()+1); } } $allCartsForEmail->clear(); - $allCarts[$this->_counter]['method'] = 'DELETE'; - $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $cartId; - $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartId; - $allCarts[$this->_counter]['body'] = ''; + $counter = $this->getCounter(); + $allCarts[$counter]['method'] = 'DELETE'; + $allCarts[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $cartId; + $allCarts[$counter]['operation_id'] = $batchId . '_' . $cartId; + $allCarts[$counter]['body'] = ''; $this->_updateSyncData($cartId, $mailchimpStoreId, null, null, null, null, 1); - $this->_counter += 1; + $this->setCounter($this->getCounter()+1); } return $allCarts; @@ -108,11 +111,12 @@ protected function _getConvertedQuotes($mailchimpStoreId, $magentoStoreId) * @param $magentoStoreId * @return array */ - protected function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) + public function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) { - $mailchimpTableName = Mage::getSingleton('core/resource')->getTableName('mailchimp/ecommercesyncdata'); + $mailchimpTableName = $this->getMailchimpEcommerceDataTableName(); + $batchId = $this->getBatchId(); $allCarts = array(); - $modifiedCarts = Mage::getResourceModel('sales/quote_collection'); + $modifiedCarts = $this->getQuoteCollection(); // select carts with no orders $modifiedCarts->addFieldToFilter('is_active', array('eq' => 1)); // select carts for the current Magento store id @@ -133,28 +137,24 @@ protected function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) $modifiedCarts->getSelect()->limit($this->getBatchLimitFromConfig()); foreach ($modifiedCarts as $cart) { $cartId = $cart->getEntityId(); - $allCarts[$this->_counter]['method'] = 'DELETE'; - $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $cartId; - $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartId; - $allCarts[$this->_counter]['body'] = ''; - $this->_counter += 1; /** * @var $customer Mage_Customer_Model_Customer */ - $customer = Mage::getModel("customer/customer"); - $customer->setWebsiteId(Mage::getModel('core/store')->load($magentoStoreId)->getWebsiteId()); + $customer = $this->getCustomerModel(); + $customer->setWebsiteId($this->getWebSiteIdFromMagentoStoreId($magentoStoreId)); $customer->loadByEmail($cart->getCustomerEmail()); if ($customer->getEmail() != $cart->getCustomerEmail()) { - $allCartsForEmail = $this->_getAllCartsByEmail($cart->getCustomerEmail(), $mailchimpStoreId, $magentoStoreId); + $allCartsForEmail = $this->getAllCartsByEmail($cart->getCustomerEmail(), $mailchimpStoreId, $magentoStoreId); foreach ($allCartsForEmail as $cartForEmail) { $alreadySentCartId = $cartForEmail->getEntityId(); + $counter = $this->getCounter(); if ($alreadySentCartId != $cartId) { - $allCarts[$this->_counter]['method'] = 'DELETE'; - $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $alreadySentCartId; - $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $alreadySentCartId; - $allCarts[$this->_counter]['body'] = ''; + $allCarts[$counter]['method'] = 'DELETE'; + $allCarts[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $alreadySentCartId; + $allCarts[$counter]['operation_id'] = $batchId . '_' . $alreadySentCartId; + $allCarts[$counter]['body'] = ''; $this->_updateSyncData($alreadySentCartId, $mailchimpStoreId, null, null, null, null, 1); - $this->_counter += 1; + $this->setCounter($this->getCounter() + 1); } } @@ -166,23 +166,23 @@ protected function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) $this->_updateSyncData($cartId, $mailchimpStoreId); continue; } - // send the products that not already sent $allCarts = $this->addProductNotSentData($mailchimpStoreId, $magentoStoreId, $cart, $allCarts); $cartJson = $this->_makeCart($cart, $mailchimpStoreId, $magentoStoreId, true); if ($cartJson != "") { - $allCarts[$this->_counter]['method'] = 'POST'; - $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts'; - $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartId; - $allCarts[$this->_counter]['body'] = $cartJson; - $this->_counter += 1; - $this->_updateSyncData($cartId, $mailchimpStoreId, null, null, null, null, null, $this->_token); + $counter = $this->getCounter(); + $allCarts[$counter]['method'] = 'PATCH'; + $allCarts[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/'.$cartId; + $allCarts[$counter]['operation_id'] = $batchId . '_' . $cartId; + $allCarts[$counter]['body'] = $cartJson; + $this->setCounter($this->getCounter()+1); + $this->_updateSyncData($cartId, $mailchimpStoreId, null, null, null, null, null, $this->getToken()); } else { $this->_updateSyncData($cartId, $mailchimpStoreId); } - $this->_token = null; + $this->setToken(null); } return $allCarts; @@ -192,11 +192,12 @@ protected function _getModifiedQuotes($mailchimpStoreId, $magentoStoreId) * @param $mailchimpStoreId * @return array */ - protected function _getNewQuotes($mailchimpStoreId, $magentoStoreId) + public function _getNewQuotes($mailchimpStoreId, $magentoStoreId) { $helper = $this->getHelper(); + $batchId = $this->getBatchId(); $allCarts = array(); - $newCarts = Mage::getResourceModel('sales/quote_collection'); + $newCarts = $this->getQuoteCollection(); $newCarts->addFieldToFilter('is_active', array('eq' => 1)); $newCarts->addFieldToFilter('customer_email', array('notnull' => true)); $newCarts->addFieldToFilter('items_count', array('gt' => 0)); @@ -204,8 +205,8 @@ protected function _getNewQuotes($mailchimpStoreId, $magentoStoreId) $newCarts->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); $helper->addResendFilter($newCarts, $magentoStoreId, Ebizmarts_MailChimp_Model_Config::IS_QUOTE); // filter by first date if exists. - if ($this->_firstDate) { - $newCarts->addFieldToFilter('updated_at', array('gt' => $this->_firstDate)); + if ($this->getFirstDate()) { + $newCarts->addFieldToFilter('updated_at', array('gt' => $this->getFirstDate())); } //join with mailchimp_ecommerce_sync_data table to filter by sync data. @@ -217,28 +218,29 @@ protected function _getNewQuotes($mailchimpStoreId, $magentoStoreId) foreach ($newCarts as $cart) { $cartId = $cart->getEntityId(); - $orderCollection = Mage::getResourceModel('sales/order_collection'); - $orderCollection->addFieldToFilter('main_table.customer_email', array('eq' => $cart->getCustomerEmail())) - ->addFieldToFilter('main_table.updated_at', array('from' => $cart->getUpdatedAt())); + $orderCollection = $this->getOrderCollection(); + $orderCollection->addFieldToFilter('main_table.customer_email', array('eq' => $cart->getCustomerEmail())); + $orderCollection->addFieldToFilter('main_table.updated_at', array('from' => $cart->getUpdatedAt())); //if cart is empty or customer has an order made after the abandonment skip current cart. if (!count($cart->getAllVisibleItems()) || $orderCollection->getSize()) { $this->_updateSyncData($cartId, $mailchimpStoreId); continue; } - $customer = Mage::getModel("customer/customer"); - $customer->setWebsiteId(Mage::getModel('core/store')->load($magentoStoreId)->getWebsiteId()); + $customer = $this->getCustomerModel(); + $customer->setWebsiteId($this->getWebSiteIdFromMagentoStoreId($magentoStoreId)); $customer->loadByEmail($cart->getCustomerEmail()); if ($customer->getEmail() != $cart->getCustomerEmail()) { - $allCartsForEmail = $this->_getAllCartsByEmail($cart->getCustomerEmail(), $mailchimpStoreId, $magentoStoreId); + $allCartsForEmail = $this->getAllCartsByEmail($cart->getCustomerEmail(), $mailchimpStoreId, $magentoStoreId); foreach ($allCartsForEmail as $cartForEmail) { + $counter = $this->getCounter(); $alreadySentCartId = $cartForEmail->getEntityId(); - $allCarts[$this->_counter]['method'] = 'DELETE'; - $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $alreadySentCartId; - $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $alreadySentCartId; - $allCarts[$this->_counter]['body'] = ''; + $allCarts[$counter]['method'] = 'DELETE'; + $allCarts[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts/' . $alreadySentCartId; + $allCarts[$counter]['operation_id'] = $batchId . '_' . $alreadySentCartId; + $allCarts[$counter]['body'] = ''; $this->_updateSyncData($alreadySentCartId, $mailchimpStoreId, null, null, null, null, 1); - $this->_counter += 1; + $this->setCounter($this->getCounter()+1); } $allCartsForEmail->clear(); @@ -255,17 +257,18 @@ protected function _getNewQuotes($mailchimpStoreId, $magentoStoreId) $cartJson = $this->_makeCart($cart, $mailchimpStoreId, $magentoStoreId); if ($cartJson != "") { - $allCarts[$this->_counter]['method'] = 'POST'; - $allCarts[$this->_counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts'; - $allCarts[$this->_counter]['operation_id'] = $this->_batchId . '_' . $cartId; - $allCarts[$this->_counter]['body'] = $cartJson; - $this->_counter += 1; - $this->_updateSyncData($cartId, $mailchimpStoreId, null, null, null, null, null, $this->_token); + $counter = $this->getCounter(); + $allCarts[$counter]['method'] = 'POST'; + $allCarts[$counter]['path'] = '/ecommerce/stores/' . $mailchimpStoreId . '/carts'; + $allCarts[$counter]['operation_id'] = $batchId . '_' . $cartId; + $allCarts[$counter]['body'] = $cartJson; + $this->setCounter($this->getCounter()+1); + $this->_updateSyncData($cartId, $mailchimpStoreId, null, null, null, null, null, $this->getToken()); } else { $this->_updateSyncData($cartId, $mailchimpStoreId); } - $this->_token = null; + $this->setToken(null); } return $allCarts; @@ -279,10 +282,10 @@ protected function _getNewQuotes($mailchimpStoreId, $magentoStoreId) * @param $magentoStoreId * @return object */ - protected function _getAllCartsByEmail($email, $mailchimpStoreId, $magentoStoreId) + public function getAllCartsByEmail($email, $mailchimpStoreId, $magentoStoreId) { - $mailchimpTableName = Mage::getSingleton('core/resource')->getTableName('mailchimp/ecommercesyncdata'); - $allCartsForEmail = Mage::getResourceModel('sales/quote_collection'); + $mailchimpTableName = $this->getMailchimpEcommerceDataTableName(); + $allCartsForEmail = $this->getQuoteCollection(); $allCartsForEmail->addFieldToFilter('is_active', array('eq' => 1)); $allCartsForEmail->addFieldToFilter('store_id', array('eq' => $magentoStoreId)); $allCartsForEmail->addFieldToFilter('customer_email', array('eq' => $email)); @@ -388,12 +391,12 @@ protected function _getCheckoutUrl($cart, $isModified) $token = $cart->getMailchimpToken(); } $url = Mage::getModel('core/url')->setStore($cart->getStoreId())->getUrl('', array('_nosid' => true, '_secure' => true)) . 'mailchimp/cart/loadquote?id=' . $cart->getEntityId() . '&token=' . $token; - $this->_token = $token; + $this->setToken($token); return $url; } /** - * @return mixed + * @return int */ protected function getBatchLimitFromConfig() { @@ -547,12 +550,15 @@ public function addProductNotSentData($mailchimpStoreId, $magentoStoreId, $cart, { $helper = $this->getHelper(); $productData = Mage::getModel('mailchimp/api_products')->sendModifiedProduct($cart, $mailchimpStoreId, $magentoStoreId); - $productDataArray = $helper->addEntriesToArray($allCarts, $productData, $this->_counter); + $productDataArray = $helper->addEntriesToArray($allCarts, $productData, $this->getCounter()); $allCarts = $productDataArray[0]; - $this->_counter = $productDataArray[1]; + $this->setCounter($productDataArray[1]); return $allCarts; } + /** + * @return Ebizmarts_MailChimp_Helper_Data + */ protected function getHelper() { return Mage::helper('mailchimp'); @@ -564,7 +570,7 @@ protected function getHelper() */ public function joinMailchimpSyncDataWithoutWhere($newCarts, $mailchimpStoreId) { - $mailchimpTableName = Mage::getSingleton('core/resource')->getTableName('mailchimp/ecommercesyncdata'); + $mailchimpTableName = $this->getMailchimpEcommerceDataTableName(); $newCarts->getSelect()->joinLeft( array('m4m' => $mailchimpTableName), "m4m.related_id = main_table.entity_id and m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_QUOTE . "' @@ -572,4 +578,108 @@ public function joinMailchimpSyncDataWithoutWhere($newCarts, $mailchimpStoreId) array('m4m.*') ); } + + /** + * @return mixed + */ + public function getMailchimpEcommerceDataTableName() + { + return Mage::getSingleton('core/resource')->getTableName('mailchimp/ecommercesyncdata'); + } + + /** + * @return Mage_Sales_Model_Resource_Quote_Collection + */ + public function getQuoteCollection() + { + return Mage::getResourceModel('sales/quote_collection'); + } + + /** + * @return false|Mage_Core_Model_Abstract + */ + public function getCustomerModel() + { + return Mage::getModel("customer/customer"); + } + + /** + * @param $magentoStoreId + * @return mixed + */ + public function getWebSiteIdFromMagentoStoreId($magentoStoreId) + { + return Mage::getModel('core/store')->load($magentoStoreId)->getWebsiteId(); + } + + /** + * @return int + */ + public function getCounter() + { + return $this->_counter; + } + + /** + * @param $counter + */ + public function setCounter($counter) + { + $this->_counter = $counter; + } + + /** + * Return the batchId for the batchJson of the carts. + * + * @return string + */ + public function getBatchId() + { + return $this->_batchId; + } + + /** + * @param $batchId + */ + public function setBatchId($batchId) + { + $this->_batchId = $batchId; + } + + /** + * Token for cart validation. + * + * @return string|null + */ + public function getToken() + { + return $this->_token; + } + /** + * @param string $token + */ + public function setToken($token) + { + + $this->_token = $token; + } + + /** + * Returns first date of abandoned cart if exists. + * + * @return string|null + */ + protected function getFirstDate() + { + return $this->_firstDate; + } + + /** + * @return Mage_Sales_Model_Resource_Order_Collection + */ + protected function getOrderCollection() + { + return Mage::getResourceModel('sales/order_collection'); + } } + diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php index db1292175..aa8cc4d0d 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Customers.php @@ -49,6 +49,8 @@ public function createBatchJson($mailchimpStoreId, $magentoStoreId) $this->optInStatusForStore = $this->getOptin($this->getBatchMagentoStoreId()); + $subscriber = $this->getSubscriberModel(); + $counter = 0; foreach ($customersCollection as $customer) { $data = $this->_buildCustomerData($customer); @@ -60,6 +62,12 @@ public function createBatchJson($mailchimpStoreId, $magentoStoreId) $this->logCouldNotEncodeCustomerError($customer); } + $isSubscribed = $subscriber->loadByEmail($customer->getEmail())->getSubscriberId(); + + if ($this->optInStatusForStore && !$isSubscribed){ + $subscriber->subscribe($customer->getEmail()); + } + $counter++; } return $customerArray; @@ -88,10 +96,10 @@ protected function _buildCustomerData($customer) $data["email_address"] = $this->getCustomerEmail($customer); $data["first_name"] = $this->getCustomerFirstname($customer); $data["last_name"] = $this->getCustomerLastname($customer); - $data["opt_in_status"] = $this->optInStatusForStore; $data["orders_count"] = (int)$customer->getOrdersCount(); $data["total_spent"] = (float)$customer->getTotalSpent(); + $data["opt_in_status"] = false; $data += $this->getCustomerAddressData($customer); @@ -432,4 +440,13 @@ protected function setMagentoStoreId($magentoStoreId) $this->magentoStoreId = $magentoStoreId; } + /** + * @return false|Mage_Core_Model_Abstract + */ + protected function getSubscriberModel() + { + $subscriber = Mage::getModel('newsletter/subscriber'); + return $subscriber; + } + } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php index dcf0439fd..f632b4e88 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Orders.php @@ -15,9 +15,9 @@ class Ebizmarts_MailChimp_Model_Api_Orders const BATCH_LIMIT = 50; const BATCH_LIMIT_ONLY_ORDERS = 500; const PAID = 'paid'; - const PARTIALLY_PAID = 'parially_paid'; + const PARTIALLY_PAID = 'partially_paid'; const SHIPPED = 'shipped'; - const PARTIALLY_SHIPPED = 'parially_shipped'; + const PARTIALLY_SHIPPED = 'partially_shipped'; const PENDING = 'pending'; const REFUNDED = 'refunded'; const PARTIALLY_REFUNDED = 'partially_refunded'; diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php index 182b1d5e6..aba388530 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Products.php @@ -327,6 +327,10 @@ protected function _buildProductData($product, $magentoStoreId, $isVariant = tru */ public function update($productId, $mailchimpStoreId) { + $parentIdArray = $this->getAllParentIds($productId); + foreach ($parentIdArray as $parentId) { + $this->_updateSyncData($parentId, $mailchimpStoreId, null, null, 1, null, null, true, false); + } $this->_updateSyncData($productId, $mailchimpStoreId, null, null, 1, null, null, true, false); } @@ -755,13 +759,23 @@ public function getProductCategories($product, $magentoStoreId) protected function getParentId($childId) { $parentId = null; - $parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($childId); + $parentIds = $this->getAllParentIds($childId); if (count($parentIds)) { $parentId = $parentIds[0]; } return $parentId; } + /** + * @param $childId + * @return mixed + */ + protected function getAllParentIds($childId) + { + $parentIds = Mage::getResourceSingleton('catalog/product_type_configurable')->getParentIdsByChild($childId); + return $parentIds; + } + /** * @param $magentoStoreId * @param $parentId diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php index 38350ac13..e6b357804 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Stores.php @@ -115,13 +115,13 @@ public function modifyName($name, $scopeId, $scope) } /** - * Returns URL from MailChimp store data + * Retrieve store data and save the MCJs URL for the correct scope in config table. * * @param $scopeId * @param $scope * @return mixed */ - public function getMCJsUrl($scopeId, $scope) + public function retrieveAndSaveMCJsUrlInConfig($scopeId, $scope) { $helper = $this->makeHelper(); try { @@ -133,14 +133,19 @@ public function getMCJsUrl($scopeId, $scope) $configValues = array(array(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_MC_JS_URL, $url)); $realScope = $helper->getRealScopeForConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, $scopeId, $scope); $helper->saveMailchimpConfig($configValues, $realScope['scope_id'], $realScope['scope']); - return $url; + return true; + } else { + return false; } } catch (Ebizmarts_MailChimp_Helper_Data_ApiKeyException $e) { $helper->logError($e->getMessage()); + return false; } catch (MailChimp_Error $e) { $helper->logError($e->getFriendlyMessage()); + return false; } catch (Exception $e) { $helper->logError($e->getMessage()); + return false; } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php index 4f026fd43..3e6de5dd0 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Api/Subscribers.php @@ -108,10 +108,33 @@ protected function _buildSubscriberData($subscriber) $data["status"] = $status; } $data["language"] = $helper->getStoreLanguageCode($storeId); + $interest = $this->_getInterest($subscriber); + if(count($interest)) { + $data['interests'] = $interest; + } return $data; } + /** + * @param $subscriber + * @return array + */ + protected function _getInterest($subscriber) + { + $storeId = $subscriber->getStoreId(); + $rc = array(); + $helper = $this->mcHelper; + $interestsAvailable = $helper->getInterest($storeId); + $interest = $helper->getInterestGroups(null, $subscriber->getSubscriberId(), $storeId, $interestsAvailable); + foreach($interest as $i) { + foreach($i['category'] as $key=>$value) { + $rc[$value['id']] = $value['checked']; + } + } + return $rc; + } + public function getMergeVars($subscriber) { $helper = $this->mcHelper; @@ -323,6 +346,7 @@ public function getMergeVars($subscriber) */ public function updateSubscriber($subscriber, $updateStatus = false) { + $saveSubscriber = false; $isAdmin = Mage::app()->getStore()->isAdmin(); $helper = $this->mcHelper; $storeId = $subscriber->getStoreId(); @@ -339,42 +363,71 @@ public function updateSubscriber($subscriber, $updateStatus = false) } $mergeVars = $this->getMergeVars($subscriber); $language = $helper->getStoreLanguageCode($storeId); + $interest = $this->_getInterest($subscriber); + $md5HashEmail = md5(strtolower($subscriber->getSubscriberEmail())); try { $api->lists->members->addOrUpdate( $listId, $md5HashEmail, $subscriber->getSubscriberEmail(), $newStatus, null, $forceStatus, $mergeVars, - null, $language, null, null + $interest, $language, null, null ); $subscriber->setData("mailchimp_sync_delta", Varien_Date::now()); $subscriber->setData("mailchimp_sync_error", ""); $subscriber->setData("mailchimp_sync_modified", 0); + $saveSubscriber = true; } catch (MailChimp_Error $e) { - if ($newStatus === 'subscribed' && $subscriber->getIsStatusChanged()) { + if ($newStatus === 'subscribed' && $subscriber->getIsStatusChanged() && !$helper->isSubscriptionConfirmationEnabled($storeId)) { if (strstr($e->getMailchimpDetails(), 'is in a compliance state')) { try { - $api->lists->members->update($listId, $md5HashEmail, null, 'pending', $mergeVars); - $subscriber->setSubscriberStatus(Mage_Newsletter_Model_Subscriber::STATUS_UNCONFIRMED); + $api->lists->members->update($listId, $md5HashEmail, null, 'pending', $mergeVars, $interest); + $subscriber->setSubscriberStatus(Mage_Newsletter_Model_Subscriber::STATUS_NOT_ACTIVE); + $saveSubscriber = true; $message = $helper->__('To begin receiving the newsletter, you must first confirm your subscription'); Mage::getSingleton('core/session')->addWarning($message); } catch (MailChimp_Error $e) { - $helper->logError($e->getFriendlyMessage()); - $this->addError($isAdmin, $e); - $subscriber->unsubscribe(); + $errorMessage = $e->getFriendlyMessage(); + $helper->logError($errorMessage); + if ($isAdmin) { + $this->addError($errorMessage); + } else { + $errorMessage = $helper->__("The subscription could not be applied."); + $this->addError($errorMessage); + } + $subscriber->setSubscriberStatus(Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED); + $saveSubscriber = true; } catch (Exception $e) { $helper->logError($e->getMessage()); } } else { - $helper->logError($e->getFriendlyMessage()); - $this->addError($isAdmin, $e); - $subscriber->unsubscribe(); + $errorMessage = $e->getFriendlyMessage(); + $helper->logError($errorMessage); + if ($isAdmin) { + $this->addError($errorMessage); + } else { + $errorMessage = $helper->__("The subscription could not be applied."); + $this->addError($errorMessage); + } + $subscriber->setSubscriberStatus(Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED); + $saveSubscriber = true; } } else { - $helper->logError($e->getFriendlyMessage()); - $this->addError($isAdmin, $e); + $errorMessage = $e->getFriendlyMessage(); + $helper->logError($errorMessage); + if ($isAdmin) { + $this->addError($errorMessage); + } else { + $errorMessage = $helper->__("The subscription could not be applied."); + $this->addError($errorMessage); + } + $subscriber->setSubscriberStatus(Mage_Newsletter_Model_Subscriber::STATUS_UNSUBSCRIBED); } } catch (Exception $e) { $helper->logError($e->getMessage()); } + if ($saveSubscriber) { + $subscriber->setSubscriberSource(Ebizmarts_MailChimp_Model_Subscriber::SUBSCRIBE_SOURCE); + $subscriber->save(); + } } } @@ -455,9 +508,8 @@ public function deleteSubscriber($subscriber) public function update($emailAddress, $storeId) { - $helper = $this->mcHelper; $subscriber = Mage::getSingleton('newsletter/subscriber')->loadByEmail($emailAddress); - if ($subscriber->getStatus() == Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED && $subscriber->getMailchimpSyncDelta() != $helper->getSubMinSyncDateFlag($storeId)) { + if ($subscriber->getId()) { $subscriber->setMailchimpSyncModified(1) ->save(); } @@ -501,13 +553,10 @@ protected function getAddressData($address) } /** - * @param $isAdmin - * @param $e + * @param $errorMessage */ - protected function addError($isAdmin, $e) + protected function addError($errorMessage) { - if ($isAdmin) { - Mage::getSingleton('core/session')->addError($e->getFriendlyMessage()); - } + Mage::getSingleton('core/session')->addError($errorMessage); } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Config.php b/app/code/community/Ebizmarts/MailChimp/Model/Config.php index 86fc29bbb..8c21c1216 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Config.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Config.php @@ -11,31 +11,35 @@ */ class Ebizmarts_MailChimp_Model_Config { - const GENERAL_ACTIVE = 'mailchimp/general/active'; - const GENERAL_APIKEY = 'mailchimp/general/apikey'; - const GENERAL_OAUTH_WIZARD = 'mailchimp/general/oauth_wizard'; - const GENERAL_ACCOUNT_DETAILS = 'mailchimp/general/account_details'; - const GENERAL_LIST = 'mailchimp/general/list'; - const GENERAL_OLD_LIST = 'mailchimp/general/old_list'; - const GENERAL_LIST_CHANGED_SCOPES = 'mailchimp/general/list_changed_scopes'; - const GENERAL_CHECKOUT_SUBSCRIBE = 'mailchimp/general/checkout_subscribe'; - const GENERAL_MCSTOREID = 'mailchimp/general/storeid'; - const GENERAL_MCISSYNCING = 'mailchimp/general/is_syicing'; - const GENERAL_ECOMMMINSYNCDATEFLAG = 'mailchimp/general/mcminsyncdateflag'; - const GENERAL_SUBMINSYNCDATEFLAG = 'mailchimp/general/subminsyncdateflag'; - const GENERAL_TWO_WAY_SYNC = 'mailchimp/general/webhook_active'; - const GENERAL_UNSUBSCRIBE = 'mailchimp/general/webhook_delete'; - const GENERAL_WEBHOOK_ID = 'mailchimp/general/webhook_id'; - const GENERAL_LOG = 'mailchimp/general/enable_log'; - const GENERAL_ORDER_GRID = 'mailchimp/general/order_grid'; - const GENERAL_MAP_FIELDS = 'mailchimp/general/map_fields'; - const GENERAL_CUSTOM_MAP_FIELDS = 'mailchimp/general/customer_map_fields'; - const GENERAL_MIGRATE_FROM_115 = 'mailchimp/general/migrate_from_115'; - const GENERAL_MIGRATE_FROM_116 = 'mailchimp/general/migrate_from_116'; - const GENERAL_MIGRATE_FROM_1164 = 'mailchimp/general/migrate_from_1164'; - const GENERAL_MIGRATE_LAST_ORDER_ID = 'mailchimp/general/migrate_last_order_id'; - const GENERAL_SUBSCRIBER_AMOUNT = 'mailchimp/general/subscriber_batch_amount'; - const GENERAL_TIME_OUT = 'mailchimp/general/connection_timeout'; + const GENERAL_ACTIVE = 'mailchimp/general/active'; + const GENERAL_APIKEY = 'mailchimp/general/apikey'; + const GENERAL_OAUTH_WIZARD = 'mailchimp/general/oauth_wizard'; + const GENERAL_ACCOUNT_DETAILS = 'mailchimp/general/account_details'; + const GENERAL_LIST = 'mailchimp/general/list'; + const GENERAL_OLD_LIST = 'mailchimp/general/old_list'; + const GENERAL_LIST_CHANGED_SCOPES = 'mailchimp/general/list_changed_scopes'; + const GENERAL_CHECKOUT_SUBSCRIBE = 'mailchimp/general/checkout_subscribe'; + const GENERAL_MCSTOREID = 'mailchimp/general/storeid'; + const GENERAL_MCISSYNCING = 'mailchimp/general/is_syicing'; + const GENERAL_ECOMMMINSYNCDATEFLAG = 'mailchimp/general/mcminsyncdateflag'; + const GENERAL_SUBMINSYNCDATEFLAG = 'mailchimp/general/subminsyncdateflag'; + const GENERAL_TWO_WAY_SYNC = 'mailchimp/general/webhook_active'; + const GENERAL_UNSUBSCRIBE = 'mailchimp/general/webhook_delete'; + const GENERAL_WEBHOOK_ID = 'mailchimp/general/webhook_id'; + const GENERAL_LOG = 'mailchimp/general/enable_log'; + const GENERAL_ORDER_GRID = 'mailchimp/general/order_grid'; + const GENERAL_MAP_FIELDS = 'mailchimp/general/map_fields'; + const GENERAL_CUSTOM_MAP_FIELDS = 'mailchimp/general/customer_map_fields'; + const GENERAL_MIGRATE_FROM_115 = 'mailchimp/general/migrate_from_115'; + const GENERAL_MIGRATE_FROM_116 = 'mailchimp/general/migrate_from_116'; + const GENERAL_MIGRATE_FROM_1164 = 'mailchimp/general/migrate_from_1164'; + const GENERAL_MIGRATE_LAST_ORDER_ID = 'mailchimp/general/migrate_last_order_id'; + const GENERAL_SUBSCRIBER_AMOUNT = 'mailchimp/general/subscriber_batch_amount'; + const GENERAL_TIME_OUT = 'mailchimp/general/connection_timeout'; + const GENERAL_INTEREST_CATEGORIES = 'mailchimp/general/interest_categories'; + const GENERAL_INTEREST_SUCCESS_BEFORE = 'mailchimp/general/interest_success_before'; + const GENERAL_INTEREST_SUCCESS_AFTER = 'mailchimp/general/interest_success_after'; + const GENERAL_MAGENTO_MAIL = 'mailchimp/general/magento_mail'; const ECOMMERCE_ACTIVE = 'mailchimp/ecommerce/active'; diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php b/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php index 0432cc89c..05f561cd3 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Email/Template.php @@ -230,7 +230,13 @@ protected function getSendingSetReturnPath() */ protected function getSendersDomains($mail) { - return $mail->senders->domains(); + $mandrillSenders = array(); + try { + $mandrillSenders = $mail->senders->domains(); + } catch (Exception $e) { + Mage::log($e->getMessage(), null, 'Mandrill.log', true); + } + return $mandrillSenders; } /** @@ -240,7 +246,13 @@ protected function getSendersDomains($mail) */ protected function sendMail($email, $mail) { - return $mail->messages->send($email); + $mailSent = false; + try { + $mailSent = $mail->messages->send($email); + } catch (Exception $e) { + Mage::log($e->getMessage(), null, 'Mandrill.log', true); + } + return $mailSent; } /** diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Interestgroup.php b/app/code/community/Ebizmarts/MailChimp/Model/Interestgroup.php new file mode 100644 index 000000000..ee07540cb --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Interestgroup.php @@ -0,0 +1,32 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 5/16/16 6:23 PM + * @file: Interestgroup.php + */ + +class Ebizmarts_MailChimp_Model_Interestgroup extends Mage_Core_Model_Abstract +{ + /** + * Initialize model + * + * @return void + */ + public function _construct() + { + parent::_construct(); + $this->_init('mailchimp/interestgroup'); + } + + public function getByRelatedIdStoreId($customerId, $subscriberId, $storeId) + { + $this->addData($this->getResource()->getByRelatedIdStoreId($customerId, $subscriberId, $storeId)); + return $this; + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Interestgroup.php b/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Interestgroup.php new file mode 100644 index 000000000..746001e44 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Interestgroup.php @@ -0,0 +1,42 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 6/9/16 4:46 PM + * @file: Interestgroup.php + */ +class Ebizmarts_MailChimp_Model_Mysql4_Interestgroup extends Mage_Core_Model_Mysql4_Abstract +{ + + /** + * Initialize + * + * @return void + */ + public function _construct() + { + $this->_init('mailchimp/interestgroup', 'id'); + } + + public function getByRelatedIdStoreId($customerId = 0, $subscriberId = 0, $storeId) + { + $read = $this->_getReadAdapter(); + $select = $read->select() + ->from($this->getMainTable()) + ->where('store_id = ?', $storeId) + ->where('(' . $read->quoteInto('customer_id = ?', $customerId) . ' OR ' . $read->quoteInto('subscriber_id = ?', $subscriberId) . ')'); + + $result = $read->fetchRow($select); + + if (!$result) { + return array(); + } + + return $result; + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Interestgroup/Collection.php b/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Interestgroup/Collection.php new file mode 100755 index 000000000..2352d3cb4 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/Mysql4/Interestgroup/Collection.php @@ -0,0 +1,27 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 5/16/16 6:53 PM + * @file: Collection.php + */ + +class Ebizmarts_MailChimp_Model_Mysql4_Interestgroup_Collection extends Mage_Core_Model_Mysql4_Collection_Abstract +{ + + /** + * Set resource type + * + * @return void + */ + public function _construct() + { + parent::_construct(); + $this->_init('mailchimp/interestgroup'); + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php index 4eeb69bc9..c7de0cdf1 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Observer.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Observer.php @@ -111,7 +111,7 @@ protected function getCustomerModel() */ public function saveConfig(Varien_Event_Observer $observer) { - $post = Mage::app()->getRequest()->getPost(); + $post = $this->getRequest()->getPost(); $helper = $this->makeHelper(); $scopeArray = $helper->getCurrentScope(); @@ -126,31 +126,57 @@ public function saveConfig(Varien_Event_Observer $observer) } /** - * Handle subscription change (subscribe/unsubscribe) + * Handle confirmation emails and subscription to Mailchimp * * @param Varien_Event_Observer $observer * @return Varien_Event_Observer + * @throws Mage_Core_Exception + */ + public function subscriberSaveBefore(Varien_Event_Observer $observer) + { + $subscriber = $observer->getEvent()->getSubscriber(); + $storeId = $subscriber->getStoreId(); + $helper = $this->makeHelper(); + $isEnabled = $helper->isSubscriptionEnabled($storeId); + + if ($isEnabled && $subscriber->getSubscriberSource() != Ebizmarts_MailChimp_Model_Subscriber::SUBSCRIBE_SOURCE) { + $statusChanged = $subscriber->getIsStatusChanged(); + + //Override Magento status to always send double opt-in confirmation. + if ($statusChanged && $subscriber->getStatus() == Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED && $helper->isSubscriptionConfirmationEnabled($storeId) && !$helper->isUseMagentoEmailsEnabled($storeId)) { + $subscriber->setStatus(Mage_Newsletter_Model_Subscriber::STATUS_NOT_ACTIVE); + $this->addSuccessIfRequired($helper); + } + + } + + return $observer; + } + + /** + * Handle interest groups for subscriber and allow Magento email to be sent if configured that way. + * + * @param Varien_Event_Observer $observer + * @return Varien_Event_Observer + * @throws Mage_Core_Exception * @throws Mage_Core_Model_Store_Exception */ - public function handleSubscriber(Varien_Event_Observer $observer) + public function subscriberSaveAfter(Varien_Event_Observer $observer) { $subscriber = $observer->getEvent()->getSubscriber(); + $storeId = $subscriber->getStoreId(); $helper = $this->makeHelper(); - if ($subscriber->getSubscriberSource() != Ebizmarts_MailChimp_Model_Subscriber::SUBSCRIBE_SOURCE) { - $storeId = $subscriber->getStoreId(); - $isEnabled = $helper->isSubscriptionEnabled($storeId); - if ($isEnabled) { - $statusChanged = $subscriber->getIsStatusChanged(); - //Override Magento status to always send double opt-in confirmation. - if($statusChanged && $subscriber->getStatus() == Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED && $helper->isSubscriptionConfirmationEnabled($storeId)) { - $subscriber->setStatus(Mage_Newsletter_Model_Subscriber::STATUS_NOT_ACTIVE); - $this->addSuccessIfRequired($helper); - } - $apiSubscriber = $this->makeApiSubscriber(); - $subscriber->setImportMode(true); - $this->createEmailCookie($subscriber); + $isEnabled = $helper->isSubscriptionEnabled($storeId); + + if ($isEnabled && $subscriber->getSubscriberSource() != Ebizmarts_MailChimp_Model_Subscriber::SUBSCRIBE_SOURCE) { + $params = $this->getRequest()->getParams(); + $helper->saveInterestGroupData($params, $storeId, null, $subscriber); - if ($statusChanged) { + $this->createEmailCookie($subscriber); + + if ($helper->isUseMagentoEmailsEnabled($storeId) != 1) { + $apiSubscriber = $this->makeApiSubscriber(); + if ($subscriber->getIsStatusChanged()) { $apiSubscriber->updateSubscriber($subscriber, true); } else { $origData = $subscriber->getOrigData(); @@ -161,6 +187,8 @@ public function handleSubscriber(Varien_Event_Observer $observer) $apiSubscriber->updateSubscriber($subscriber, true); } } + } else { + $subscriber->setImportMode(false); } } @@ -227,40 +255,49 @@ public function alterNewsletterGrid(Varien_Event_Observer $observer) * @param Varien_Event_Observer $observer * @return Varien_Event_Observer */ - public function customerSaveBefore(Varien_Event_Observer $observer) + public function customerSaveAfter(Varien_Event_Observer $observer) { $customer = $observer->getEvent()->getCustomer(); + $origEmail = $customer->getOrigData('email'); + $customerEmail = $customer->getEmail(); $storeId = $customer->getStoreId(); + // if customer was created in admin, use store id selected for Mailchimp. + if (!$storeId) { + $storeId = $customer->getMailchimpStoreView(); + } $helper = $this->makeHelper(); $isEnabled = $helper->isSubscriptionEnabled($storeId); + $params = $this->getRequest()->getParams(); if ($isEnabled) { + $customerId = $customer->getId(); + $subscriberEmail = ($origEmail) ? $origEmail : $customerEmail; + $subscriber = $this->handleCustomerGroups($subscriberEmail, $params, $storeId, $customerId); $apiSubscriber = $this->makeApiSubscriber(); - $origEmail = $customer->getOrigData('email'); - $customerEmail = $customer->getEmail(); if ($origEmail) { // check if customer has changed email address if ($origEmail != $customerEmail) { - $subscriberModel = $this->getSubscriberModel(); - $subscriber = $subscriberModel->loadByEmail($origEmail); if ($subscriber->getId()) { // unsubscribe old email address $apiSubscriber->deleteSubscriber($subscriber); // subscribe new email address + $subscriberModel = $this->getSubscriberModel(); $subscriber = $subscriberModel->loadByCustomer($customer); $subscriber->setSubscriberEmail($customerEmail); // make sure we set the new email address + $subscriber->save(); - $apiSubscriber->updateSubscriber($subscriber, true); } } } - //update subscriber data if a subscriber with the same email address exists - $apiSubscriber->update($customerEmail, $storeId); + //update subscriber data if a subscriber with the same email address exists and was not affected. + if (!$origEmail || $origEmail == $customerEmail) { + $apiSubscriber->update($customerEmail, $storeId); + } if ($helper->isEcomSyncDataEnabled($storeId)) { //update mailchimp ecommerce data for that customer - $this->makeApiCustomer()->update($customer->getId(), $storeId); + $this->makeApiCustomer()->update($customerId, $storeId); } } @@ -308,7 +345,7 @@ public function newOrder(Varien_Event_Observer $observer) $email = $order->getCustomerEmail(); $subscriber = $helper->loadListSubscriber($post, $email); if ($subscriber) { - if(!$subscriber->getCustomerId()) { + if (!$subscriber->getCustomerId()) { $subscriber->setSubscriberFirstname($order->getCustomerFirstname()); $subscriber->setSubscriberLastname($order->getCustomerLastname()); } @@ -427,10 +464,9 @@ public function addOrderViewMonkey(Varien_Event_Observer $observer) $order = $block->getOrder(); $storeId = $order->getStoreId(); $helper = $this->makeHelper(); - $addColumnConfig = $helper->getMonkeyInGrid($storeId); $ecommEnabled = $helper->isEcomSyncDataEnabled($storeId); - if ($ecommEnabled && $addColumnConfig) { + if ($ecommEnabled) { $transport = $observer->getTransport(); if ($transport) { $html = $transport->getHtml(); @@ -496,7 +532,6 @@ public function addColumnToSalesOrderGrid(Varien_Event_Observer $observer) } - public function addColumnToSalesOrderGridCollection(Varien_Event_Observer $observer) { @@ -686,7 +721,7 @@ public function productSaveBefore(Varien_Event_Observer $observer) $ecommEnabled = $helper->isEcommerceEnabled($scopeArray['scope_id'], $scopeArray['scope']); if ($ecommEnabled) { - if ($product->getStatus() == self::PRODUCT_IS_DISABLED){ + if ($product->getStatus() == self::PRODUCT_IS_DISABLED) { $apiProduct->updateDisabledProducts($product->getId(), $mailchimpStoreId); } else { $apiProduct->update($product->getId(), $mailchimpStoreId); @@ -843,7 +878,7 @@ public function salesruleDeleteAfter(Varien_Event_Observer $observer) public function secondaryCouponsDelete(Varien_Event_Observer $observer) { $promoCodesApi = $this->makeApiPromoCode(); - $params = Mage::app()->getRequest()->getParams(); + $params = $this->getRequest()->getParams(); if (isset($params['ids']) && isset($params['id'])) { $promoRuleId = $params['id']; $promoCodeIds = $params['ids']; @@ -962,6 +997,66 @@ protected function createEmailCookie($subscriber) } } + public function addCustomerTab(Varien_Event_Observer $observer) + { + $block = $observer->getEvent()->getBlock(); + $helper = $this->makeHelper(); + // add tab in customer edit page + if ($block instanceof Mage_Adminhtml_Block_Customer_Edit_Tabs) { + $customerId = (int)$this->getRequest()->getParam('id'); + $customer = Mage::getModel('customer/customer')->load($customerId); + $storeId = $customer->getStoreId(); + //If the customer was created in the admin panel use the store view selected for MailChimp. + if (!$storeId) { + $storeId = $customer->getMailchimpStoreView(); + } + if ($helper->getLocalInterestCategories($storeId) && ($this->getRequest()->getActionName() == 'edit' || $this->getRequest()->getParam('type'))) { + $block->addTab('mailchimp', array( + 'label' => $helper->__('MailChimp'), + 'url' => $block->getUrl('adminhtml/mailchimp/index', array('_current' => true)), + 'class' => 'ajax' + )); + + } + } + return $observer; + } + + protected function getRequest() + { + return Mage::app()->getRequest(); + } + + /** + * Handle frontend customer interest groups only if is not subscribed and all admin customer groups. + * + * @param $subscriberEmail + * @param $params + * @param $storeId + * @param null $customerId + * @return Mage_Newsletter_Model_Subscriber + * @throws Mage_Core_Model_Store_Exception + */ + public function handleCustomerGroups($subscriberEmail, $params, $storeId, $customerId = null) + { + $helper = $this->makeHelper(); + $subscriberModel = $this->getSubscriberModel(); + $subscriber = $subscriberModel->loadByEmail($subscriberEmail); + if ($subscriber->getId()) { + $helper->saveInterestGroupData($params, $storeId, $customerId, $subscriber); + } elseif (isset($params['customer_id'])) { + $groups = $helper->getInterestGroupsIfAvailable($params); + if ($groups) { + $helper->saveInterestGroupData($params, $storeId, $customerId); + $this->getWarningMessageAdminHtmlSession($helper); + } + } else { + //save frontend groupdata when customer is not subscribed. + $helper->saveInterestGroupData($params, $storeId, $customerId); + } + return $subscriber; + } + /** * @return mixed */ @@ -993,6 +1088,15 @@ protected function isCustomerLoggedIn() */ protected function getRequestActionName() { - return Mage::app()->getRequest()->getActionName(); + return $this->getRequest()->getActionName(); + } + + /** + * @param $helper + * @return mixed + */ + protected function getWarningMessageAdminHtmlSession($helper) + { + return Mage::getSingleton('adminhtml/session')->addWarning($helper->__('The customer must be subscribed for this change to apply.')); } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php b/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php index 7a3f26f05..a33f31433 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/ProcessWebhook.php @@ -263,20 +263,12 @@ protected function _profile(array $data) public function deleteProcessed() { - $to= Mage::app()->getLocale()->date()->sub(30,Zend_Date::DAY); - $to=$to->toString('yyyy-MM-dd'); - - $collection = Mage::getModel('mailchimp/webhookrequest')->getCollection() - ->addFieldToFilter('processed', 1) - ->addFieldToFilter('fired_at', array( - 'lt'=>$to - )); - $collection->getSelect()->limit(self::BATCH_LIMIT); - - foreach ($collection as $row) { - $row->delete(); - } - + $helper = $this->getHelper(); + $resource = $helper->getCoreResource(); + $connection = $resource->getConnection('core_write'); + $tableName = $resource->getTableName('mailchimp/webhookrequest'); + $where = array("fired_at < NOW() - INTERVAL 30 DAY AND processed = 1"); + $connection->delete($tableName, $where); } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/Subscriber.php b/app/code/community/Ebizmarts/MailChimp/Model/Subscriber.php index ba61537a5..efc4ee10c 100755 --- a/app/code/community/Ebizmarts/MailChimp/Model/Subscriber.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/Subscriber.php @@ -12,7 +12,7 @@ class Ebizmarts_MailChimp_Model_Subscriber extends Mage_Newsletter_Model_Subscri public function sendUnsubscriptionEmail() { - if (Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE)) { + if (Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE) && Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MAGENTO_MAIL) != 1) { return $this; } else { return parent::sendUnsubscriptionEmail(); @@ -21,7 +21,7 @@ public function sendUnsubscriptionEmail() public function sendConfirmationRequestEmail() { - if (Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE)) { + if (Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE) && Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MAGENTO_MAIL) != 1) { return $this; } else { return parent::sendConfirmationRequestEmail(); @@ -30,10 +30,23 @@ public function sendConfirmationRequestEmail() public function sendConfirmationSuccessEmail() { - if (Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE)) { + if (Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_ACTIVE) && Mage::getStoreConfig(Ebizmarts_MailChimp_Model_Config::GENERAL_MAGENTO_MAIL) != 1) { return $this; } else { return parent::sendConfirmationSuccessEmail(); } } + + public function confirm($code) + { + if($this->getCode()==$code) { + $this->setStatus(self::STATUS_SUBSCRIBED) + ->setIsStatusChanged(true) + ->setSubscriberSource(Ebizmarts_MailChimp_Model_Subscriber::SUBSCRIBE_SOURCE) + ->save(); + return true; + } + + return false; + } } diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/CustomerGroup.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/CustomerGroup.php new file mode 100644 index 000000000..7744760b6 --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/CustomerGroup.php @@ -0,0 +1,53 @@ + + * Date : 8/29/14 + * Time : 3:36 PM + * File : CustomerGroup.php + * Module : magemonkey + */ +class Ebizmarts_MailChimp_Model_System_Config_Source_CustomerGroup +{ + protected $_categories = null; + + /** + * Load lists and store on class property + */ + public function __construct() + { + $helper = $this->makeHelper(); + $scopeArray = $helper->getCurrentScope(); + if ($helper->isSubscriptionEnabled($scopeArray['scope_id'], $scopeArray['scope'])) { + $this->_categories = $helper->getListInterestCategories($scopeArray['scope_id'], $scopeArray['scope']); + } + } + + /** + * Options getter + * + * @return array + */ + public function toOptionArray() + { + $groups = array(); + $helper = $this->makeHelper(); + if (is_array($this->_categories)) { + foreach ($this->_categories as $category) { + $groups[] = array('value'=> $category['id'], 'label' => $category['title']); + } + } else { + $groups []= array('value' => '', 'label' => $helper->__('--- No data ---')); + } + return $groups; + } + + /** + * @return Ebizmarts_MailChimp_Helper_Data + */ + protected function makeHelper() + { + return Mage::helper('mailchimp'); + } + +} diff --git a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/ImageSize.php b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/ImageSize.php index b1373fef4..98da5f791 100644 --- a/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/ImageSize.php +++ b/app/code/community/Ebizmarts/MailChimp/Model/System/Config/Source/ImageSize.php @@ -12,6 +12,7 @@ class Ebizmarts_MailChimp_Model_System_Config_Source_ImageSize const BASE = 0; const SMALL = 1; const THUMBNAIL = 2; + const ORIGINAL = 3; /** @@ -25,8 +26,8 @@ public function toOptionArray() return array( array('value' => self::BASE, 'label' => $helper->__('Base')), array('value' => self::SMALL, 'label' => $helper->__('Small')), - array('value' => self::THUMBNAIL, 'label' => $helper->__('Thumbnail')) - + array('value' => self::THUMBNAIL, 'label' => $helper->__('Thumbnail')), + array('value' => self::ORIGINAL, 'label' => $helper->__('Original')) ); } } diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpController.php b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpController.php index 8e07cdb7a..7a64dc987 100644 --- a/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpController.php +++ b/app/code/community/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpController.php @@ -12,6 +12,19 @@ */ class Ebizmarts_MailChimp_Adminhtml_MailchimpController extends Mage_Adminhtml_Controller_Action { + public function indexAction() + { + $customerId = (int) $this->getRequest()->getParam('id'); + if ($customerId) { + $block = $this->getLayout() + ->createBlock('mailchimp/adminhtml_customer_edit_tab_mailchimp', 'admin.customer.mailchimp') + ->setCustomerId($customerId) + ->setUseAjax(true); + $html = $this->getHtml($block); + $this->getResponse()->setBody($html); + } + } + public function resendSubscribersAction() { $helper = $this->makeHelper(); @@ -47,10 +60,13 @@ public function createWebhookAction() protected function _isAllowed() { + $acl = null; switch ($this->getRequest()->getActionName()) { - case 'resendSubscribers': - $acl = 'system/config/mailchimp'; - break; + case 'index': + case 'resendSubscribers': + case 'createWebhook': + $acl = 'system/config/mailchimp'; + break; } return Mage::getSingleton('admin/session')->isAllowed($acl); @@ -63,4 +79,13 @@ protected function makeHelper() { return Mage::helper('mailchimp'); } + + /** + * @param $block + * @return mixed + */ + protected function getHtml($block) + { + return $block->toHtml(); + } } diff --git a/app/code/community/Ebizmarts/MailChimp/controllers/GroupController.php b/app/code/community/Ebizmarts/MailChimp/controllers/GroupController.php new file mode 100644 index 000000000..c6a67acdc --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/controllers/GroupController.php @@ -0,0 +1,105 @@ + + * @copyright Ebizmarts (http://ebizmarts.com) + * @license http://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) + * @date: 7/6/16 10:14 AM + * @file: GroupController.php + */ + + +class Ebizmarts_MailChimp_GroupController extends Mage_Core_Controller_Front_Action +{ + public function indexAction() + { + $helper = $this->getHelper(); + $order = $this->getSessionLastRealOrder(); + $session = $this->getCoreSession(); + $interestGroup = $this->getInterestGroupModel(); + $params = $this->getRequest()->getParams(); + $storeId = $order->getStoreId(); + $customerEmail = $order->getCustomerEmail(); + $customerId = $order->getCustomerId(); + $subscriber = $this->getSubscriberModel() + ->loadByEmail($customerEmail); + try { + if (!$subscriber->getSubscriberId()) { + $subscriber->setSubscriberEmail($customerEmail); + $subscriber->setSubscriberFirstname($order->getCustomerFirstname()); + $subscriber->setSubscriberLastname($order->getCustomerLastname()); + $subscriber->subscribe($customerEmail); + } + $subscriberId = $subscriber->getSubscriberId(); + $interestGroup->getByRelatedIdStoreId($customerId, $subscriberId, $storeId); + $encodedGroups = $helper->arrayEncode($params); + $interestGroup->setGroupdata($encodedGroups); + $interestGroup->setSubscriberId($subscriberId); + $interestGroup->setCustomerId($customerId); + $interestGroup->setStoreId($storeId); + $interestGroup->setUpdatedAt($this->getCurrentDateTime()); + $interestGroup->save(); + + $this->getApiSubscriber()->update($subscriber->getSubscriberEmail(), $storeId, '', 1); + + $session->addSuccess($this->__('Thanks for share your interest with us.')); + } catch (Exception $e) { + $helper->logError($e->getMessage()); + $session->addWarning($this->__('Something went wrong with the interests subscription. Please go to the account subscription menu to subscriber to the interests successfully.')); + } + $this->_redirect('/'); + } + + protected function getHelper() + { + return Mage::helper('mailchimp'); + } + + protected function getApiSubscriber() + { + return Mage::getModel('mailchimp/api_subscribers'); + } + + /** + * @return mixed + */ + protected function getSessionLastRealOrder() + { + return Mage::getSingleton('checkout/session')->getLastRealOrder(); + } + + /** + * @return Mage_Core_Model_Session + */ + protected function getCoreSession() + { + return Mage::getSingleton('core/session'); + } + + /** + * @return Ebizmarts_MailChimp_Model_Interestgroup + */ + protected function getInterestGroupModel() + { + return Mage::getModel('mailchimp/interestgroup'); + } + + /** + * @return Mage_Newsletter_Model_Subscriber + */ + protected function getSubscriberModel() + { + return Mage::getModel('newsletter/subscriber'); + } + + /** + * @return mixed + */ + protected function getCurrentDateTime() + { + return Mage::getModel('core/date')->date('d-m-Y H:i:s'); + } +} diff --git a/app/code/community/Ebizmarts/MailChimp/etc/config.xml b/app/code/community/Ebizmarts/MailChimp/etc/config.xml index d03617831..e393b300c 100755 --- a/app/code/community/Ebizmarts/MailChimp/etc/config.xml +++ b/app/code/community/Ebizmarts/MailChimp/etc/config.xml @@ -3,10 +3,10 @@ - 1.1.14 + 1.1.15 - 1.1.14 + 1.1.15 @@ -31,10 +31,18 @@ mailchimp/observer - handleSubscriber + subscriberSaveBefore + + + + mailchimp/observer + subscriberSaveAfter + + + @@ -43,15 +51,15 @@ - + - + model mailchimp/observer - customerSaveBefore - + customerSaveAfter + - + @@ -162,6 +170,9 @@ mailchimp_ecommerce_sync_data
+ + mailchimp_interest_group
+
@@ -302,6 +313,15 @@ + + + + model + mailchimp/observer + addCustomerTab + + + @@ -431,7 +451,7 @@ - 0 */1 * * * + 0 0 * * * mailchimp/cron::deleteWebhookRequests diff --git a/app/code/community/Ebizmarts/MailChimp/etc/system.xml b/app/code/community/Ebizmarts/MailChimp/etc/system.xml index caae10e2a..8ae2ba87b 100755 --- a/app/code/community/Ebizmarts/MailChimp/etc/system.xml +++ b/app/code/community/Ebizmarts/MailChimp/etc/system.xml @@ -85,7 +85,7 @@ button mailchimp/adminhtml_system_config_resetErrors - 45 + 42 1 1 1 @@ -93,7 +93,7 @@ button mailchimp/adminhtml_system_config_resendSubscribers - 46 + 44 1 1 1 @@ -103,7 +103,7 @@ select mailchimp/system_config_source_list mailchimp/system_config_backend_list - 50 + 45 1 1 1 @@ -114,13 +114,57 @@ button mailchimp/adminhtml_system_config_resetList - 52 + 46 1 1 1 - + + + multiselect + mailchimp/system_config_source_customerGroup + 48 + 1 + 1 + 1 + 1 + + + + + select + adminhtml/system_config_source_yesno + 49 + 1 + 1 + 1 + + + + textarea + 50 + 1 + 1 + 1 + 1 + + 1 + + + + + textarea + 51 + 1 + 1 + 1 + 1 + + 1 + + + select mailchimp/system_config_source_batchLimit @@ -171,7 +215,7 @@ - + button mailchimp/adminhtml_system_config_createWebhook 58 @@ -181,7 +225,7 @@ - + select adminhtml/system_config_source_yesno mailchimp/system_config_backend_twowaysync @@ -192,6 +236,17 @@ 1 + + + select + adminhtml/system_config_source_yesno + 61 + 1 + 1 + 1 + 1 + + select @@ -224,7 +279,7 @@ - + 200 text 1 @@ -253,7 +308,7 @@ 1 - + select mailchimp/system_config_source_imageSize diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.12-1.1.13.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.12-1.1.12.2.php similarity index 64% rename from app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.12-1.1.13.php rename to app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.12-1.1.12.2.php index 217c2c996..c2d8f5754 100644 --- a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.12-1.1.13.php +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.12-1.1.12.2.php @@ -36,29 +36,32 @@ )); -$attribute = Mage::getSingleton("eav/config")->getAttribute("customer", "mailchimp_store_view"); +try { + $attribute = Mage::getSingleton("eav/config")->getAttribute("customer", "mailchimp_store_view"); -$setup->addAttributeToGroup( - $entityTypeId, - $attributeSetId, - $attributeGroupId, - 'mailchimp_store_view', - '999' //sort_order -); + $setup->addAttributeToGroup( + $entityTypeId, + $attributeSetId, + $attributeGroupId, + 'mailchimp_store_view', + '999' //sort_order + ); -$used_in_forms=array(); + $used_in_forms = array(); -$used_in_forms[]="adminhtml_customer"; + $used_in_forms[] = "adminhtml_customer"; -$attribute->setData("used_in_forms", $used_in_forms) - ->setData("is_used_for_customer_segment", true) - ->setData("is_system", 0) - ->setData("is_user_defined", 1) - ->setData("is_visible", 1) - ->setData("sort_order", 100) -; -$attribute->save(); + $attribute->setData("used_in_forms", $used_in_forms) + ->setData("is_used_for_customer_segment", true) + ->setData("is_system", 0) + ->setData("is_user_defined", 1) + ->setData("is_visible", 1) + ->setData("sort_order", 100); + $attribute->save(); +} catch (Exception $e) { + Mage::log($e->getMessage(), null, 'MailChimp_Errors.log', true); +} $installer->deleteConfigData(Ebizmarts_MailChimp_Model_Config::ENABLE_POPUP); diff --git a/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.14-1.1.15.php b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.14-1.1.15.php new file mode 100755 index 000000000..0e27c955e --- /dev/null +++ b/app/code/community/Ebizmarts/MailChimp/sql/mailchimp_setup/mysql4-upgrade-1.1.14-1.1.15.php @@ -0,0 +1,20 @@ +run( + " + CREATE TABLE IF NOT EXISTS `{$this->getTable('mailchimp_interest_group')}` ( + `id` INT(10) unsigned NOT NULL auto_increment, + `customer_id` INT(10) DEFAULT NULL, + `subscriber_id` INT(10) DEFAULT NULL, + `store_id` SMALLINT (5) NOT NULL DEFAULT 0, + `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP, + `updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP, + `groupdata` TEXT(4096) NOT NULL, + PRIMARY KEY (`id`) + ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +" +); + +$installer->endSetup(); diff --git a/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/customer/tab/mailchimp.phtml b/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/customer/tab/mailchimp.phtml new file mode 100644 index 000000000..4a08493c4 --- /dev/null +++ b/app/design/adminhtml/default/default/template/ebizmarts/mailchimp/customer/tab/mailchimp.phtml @@ -0,0 +1,76 @@ +getInterest(); +?> +
+
+ __('Mailchimp Information') ?> +
+
+
+ +
+ +
+
+ +
    + +
  • + + /> + +
  • + +
+ +
+ + +
+ +
    + +
  • + + /> + +
  • + +
+ + +
+
+
+ +
+
+
diff --git a/app/design/frontend/base/default/layout/ebizmarts/mailchimp.xml b/app/design/frontend/base/default/layout/ebizmarts/mailchimp.xml index 8ec63c01a..a4c5d768e 100755 --- a/app/design/frontend/base/default/layout/ebizmarts/mailchimp.xml +++ b/app/design/frontend/base/default/layout/ebizmarts/mailchimp.xml @@ -29,16 +29,37 @@ + template="ebizmarts/mailchimp/popup/emailcatcher.phtml"/> + + + + + + + + + + - + + + + + + + + diff --git a/app/design/frontend/base/default/template/ebizmarts/mailchimp/checkout/subscribe.phtml b/app/design/frontend/base/default/template/ebizmarts/mailchimp/checkout/subscribe.phtml index 5a411b112..986e23744 100644 --- a/app/design/frontend/base/default/template/ebizmarts/mailchimp/checkout/subscribe.phtml +++ b/app/design/frontend/base/default/template/ebizmarts/mailchimp/checkout/subscribe.phtml @@ -32,19 +32,11 @@ $generalList = $this->getGeneralList(); value: subscribeValue + element.readAttribute('value'), type: "hidden" }); -// var listValue = new Element('input', { -// name: element.readAttribute('name'), -// id: "subscribe-" + element.readAttribute('value'), -// value: element.readAttribute('value'), -// type: "hidden" -// }); try { Element.insert(Form.findFirstElement(payment.form), inputer); -// Element.insert(Form.findFirstElement(payment.form), listValue); } catch (notelem) { $("co-payment-form").insert(inputer); -// $("co-payment-form").insert(listValue); } } else { var arrCheckedLists = checkedLists.split(','); @@ -86,8 +78,7 @@ $generalList = $this->getGeneralList(); value="" title="" class="mailchimp-list-subscriber"/> - + diff --git a/app/design/frontend/base/default/template/ebizmarts/mailchimp/checkout/success/groups.phtml b/app/design/frontend/base/default/template/ebizmarts/mailchimp/checkout/success/groups.phtml new file mode 100644 index 000000000..d33935b47 --- /dev/null +++ b/app/design/frontend/base/default/template/ebizmarts/mailchimp/checkout/success/groups.phtml @@ -0,0 +1,36 @@ +getInterest(); +?> +

+ getMessageBefore() ?> +

+
+ +
+ +
+
+ getLayout()->createBlock('mailchimp/group_type', 'mailchimp.group.type', array('interests' => $i))->toHtml(); ?> +
+
+
+ +
+
+
+ +
+
+
+getMessageAfter() ?> + +

diff --git a/app/design/frontend/base/default/template/ebizmarts/mailchimp/customer/newsletter/index.phtml b/app/design/frontend/base/default/template/ebizmarts/mailchimp/customer/newsletter/index.phtml new file mode 100644 index 000000000..cc6068e99 --- /dev/null +++ b/app/design/frontend/base/default/template/ebizmarts/mailchimp/customer/newsletter/index.phtml @@ -0,0 +1,16 @@ +getInterest(); +?> +
+ +
    +
  • + +
  • + getLayout()->createBlock('mailchimp/group_type', 'mailchimp.group.type', array('interests' => $i))->toHtml(); ?> +
+ +
diff --git a/app/design/frontend/base/default/template/ebizmarts/mailchimp/group/type/checkboxes.phtml b/app/design/frontend/base/default/template/ebizmarts/mailchimp/group/type/checkboxes.phtml new file mode 100644 index 000000000..9c0bd1924 --- /dev/null +++ b/app/design/frontend/base/default/template/ebizmarts/mailchimp/group/type/checkboxes.phtml @@ -0,0 +1,19 @@ +getCurrentInterest(); +?> +
    + +
  • + + /> + +
  • + +
diff --git a/app/design/frontend/base/default/template/ebizmarts/mailchimp/group/type/dropdown.phtml b/app/design/frontend/base/default/template/ebizmarts/mailchimp/group/type/dropdown.phtml new file mode 100644 index 000000000..1769b36eb --- /dev/null +++ b/app/design/frontend/base/default/template/ebizmarts/mailchimp/group/type/dropdown.phtml @@ -0,0 +1,15 @@ +getCurrentInterest(); +?> +
+ +
diff --git a/app/design/frontend/base/default/template/ebizmarts/mailchimp/group/type/radio.phtml b/app/design/frontend/base/default/template/ebizmarts/mailchimp/group/type/radio.phtml new file mode 100644 index 000000000..a01dd058e --- /dev/null +++ b/app/design/frontend/base/default/template/ebizmarts/mailchimp/group/type/radio.phtml @@ -0,0 +1,19 @@ +getCurrentInterest(); +?> +
    + +
  • + + /> + +
  • + +
diff --git a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Block/Checkout/Success/GroupsTest.php b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Block/Checkout/Success/GroupsTest.php new file mode 100644 index 000000000..47f24a2ab --- /dev/null +++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Block/Checkout/Success/GroupsTest.php @@ -0,0 +1,81 @@ +getLayout(); + $this->_block = new Ebizmarts_MailChimp_Block_Checkout_Success_Groups; + $this->_groupsMock = $this->getMockBuilder(Ebizmarts_MailChimp_Block_Checkout_Success_Groups::class); + + /* We are required to set layouts before we can do anything with blocks */ + $this->_block->setLayout($layout); + } + + public function testGetInterest() + { + $interest = array(); + $customerEmail = 'customer@email.com'; + $subscriberId = 1; + $customerId = 2; + $storeId = 1; + + $groupsMock = $this->_groupsMock + ->disableOriginalConstructor() + ->setMethods(array('getSubscriberModel', 'getSessionLastRealOrder', 'getElementHtml', 'getMailChimpHelper')) + ->getMock(); + + $orderMock = $this->getMockBuilder(Mage_Sales_Model_Order::class) + ->disableOriginalConstructor() + ->setMethods(array('getCustomerEmail', 'getCustomerId', 'getStoreId')) + ->getMock(); + + $subscriberMock = $this->getMockBuilder(Mage_Newsletter_Model_Subscriber::class) + ->disableOriginalConstructor() + ->setMethods(array('loadByEmail', 'getSubscriberId')) + ->getMock(); + + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('getInterestGroups')) + ->getMock(); + + + $groupsMock->expects($this->once())->method('getSubscriberModel')->willReturn($subscriberMock); + $groupsMock->expects($this->once())->method('getSessionLastRealOrder')->willReturn($orderMock); + + $orderMock->expects($this->once())->method('getCustomerEmail')->willReturn($customerEmail); + + $subscriberMock->expects($this->once())->method('loadByEmail')->with($customerEmail); + $subscriberMock->expects($this->once())->method('getSubscriberId')->willReturn($subscriberId); + + $orderMock->expects($this->once())->method('getCustomerId')->willReturn($customerId); + $orderMock->expects($this->once())->method('getStoreId')->willReturn($storeId); + + $groupsMock->expects($this->once())->method('getMailChimpHelper')->willReturn($helperMock); + + $orderMock->expects($this->once())->method('getStoreId')->willReturn($storeId); + + $helperMock->expects($this->once())->method('getInterestGroups')->with($customerId, $subscriberId, $storeId)->willReturn($interest); + + $groupsMock->getInterest(); + } + +} diff --git a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Block/Customer/Newsletter/IndexTest.php b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Block/Customer/Newsletter/IndexTest.php new file mode 100644 index 000000000..ffb92a9c3 --- /dev/null +++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Block/Customer/Newsletter/IndexTest.php @@ -0,0 +1,92 @@ +getLayout(); + $this->_block = new Ebizmarts_MailChimp_Block_Customer_Newsletter_Index; + $this->_indexMock = $this->getMockBuilder(Ebizmarts_MailChimp_Block_Customer_Newsletter_Index::class); + + /* We are required to set layouts before we can do anything with blocks */ + $this->_block->setLayout($layout); + } + + public function testGetInterest() + { + $interest = array(); + $emailAddress = 'address@email.com'; + $subscriberId = 1; + $customerId = 2; + $storeId = 1; + + $indexMock = $this->_indexMock + ->disableOriginalConstructor() + ->setMethods(array('getSubscriberModel', '_getEmail', 'getMailChimpHelper', 'getCustomerSession')) + ->getMock(); + + + $subscriberMock = $this->getMockBuilder(Mage_Newsletter_Model_Subscriber::class) + ->disableOriginalConstructor() + ->setMethods(array('loadByEmail', 'getSubscriberId', 'getStoreId')) + ->getMock(); + + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('isAdmin', 'getInterestGroups')) + ->getMock(); + + $customerSessionMock = $this->getMockBuilder(Mage_Customer_Model_Session::class) + ->disableOriginalConstructor() + ->setMethods(array('isLoggedIn', 'getCustomer')) + ->getMock(); + + $customerMock = $this->getMockBuilder(Mage_Customer_Model_Customer::class) + ->disableOriginalConstructor() + ->setMethods(array('getId', 'getStoreId')) + ->getMock(); + + $indexMock->expects($this->once())->method('getSubscriberModel')->willReturn($subscriberMock); + $indexMock->expects($this->once())->method('_getEmail')->willReturn($emailAddress); + + $subscriberMock->expects($this->once())->method('loadByEmail')->with($emailAddress); + + $indexMock->expects($this->once())->method('getMailChimpHelper')->willReturn($helperMock); + $indexMock->expects($this->once())->method('getCustomerSession')->willReturn($customerSessionMock); + + $helperMock->expects($this->once())->method('isAdmin')->willReturn(false); + + $customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(true); + $customerSessionMock->expects($this->once())->method('getCustomer')->willReturn($customerMock); + + $customerMock->expects($this->once())->method('getId')->willReturn($customerId); + + $subscriberMock->expects($this->once())->method('getStoreId')->willReturn(null); + + $customerMock->expects($this->once())->method('getStoreId')->willReturn($storeId); + + $subscriberMock->expects($this->once())->method('getSubscriberId')->willReturn($subscriberId); + + $helperMock->expects($this->once())->method('getInterestGroups')->with($customerId, $subscriberId, $storeId)->willReturn($interest); + + $indexMock->getInterest(); + } + +} diff --git a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Helper/DataTest.php b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Helper/DataTest.php index d8f213864..672864cd4 100644 --- a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Helper/DataTest.php +++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Helper/DataTest.php @@ -373,22 +373,29 @@ public function testCreateWebhookIfRequired() $helperMock->createWebhookIfRequired($scopeId, $scope); } - public function testGetImageUrlById() + /** + * @param array $data + * @dataProvider testGetImageUrlByIdDataProvider + */ + + public function testGetReSizedImageUrlById($data) { $productId = 1; $magentoStoreId = 1; $defaultStoreId = 0; - $imageSize = 'image'; - $upperCaseImage = 'getImageUrl'; + $imageSize = $data['imageSize']; + $imageUrl = 'http://magento.com/catalog/product/image.jpg'; + $configImageSize = $data['configImageSize']; $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) ->disableOriginalConstructor() - ->setMethods(array('getProductResourceModel', 'getProductModel', 'getImageSize', 'getCurrentStoreId', 'setCurrentStore', 'getImageFunctionName')) + ->setMethods(array('getProductResourceModel', 'getProductModel', 'getImageSize', 'getCurrentStoreId', + 'setCurrentStore', 'getImageUrl', 'getImageUrlForSize')) ->getMock(); $productModelMock = $this->getMockBuilder(Mage_Catalog_Model_Product::class) ->disableOriginalConstructor() - ->setMethods(array('setData', 'getImageUrl')) + ->setMethods(array('setData', 'getImageUrl', 'getThumbnailUrl', 'getSmallImageUrl')) ->getMock(); $productResourceModelMock = $this->getMockBuilder(Mage_Catalog_Model_Resource_Product::class) @@ -402,22 +409,76 @@ public function testGetImageUrlById() $helperMock->expects($this->once())->method('getProductResourceModel')->willReturn($productResourceModelMock); $helperMock->expects($this->once())->method('getProductModel')->willReturn($productModelMock); - $helperMock->expects($this->once())->method('getImageSize')->with($magentoStoreId)->willReturn($imageSize); + $helperMock->expects($this->once())->method('getImageSize')->with($magentoStoreId)->willReturn($configImageSize); $productResourceModelMock->expects($this->once())->method('getAttributeRawValue')->with($productId, $imageSize, $magentoStoreId)->willReturn($imageModelMock); $productModelMock->expects($this->once())->method('setData')->with($imageSize, $imageModelMock); - $productModelMock->expects($this->once())->method('getImageUrl')->willReturn('ImageUrl'); $helperMock->expects($this->once())->method('getCurrentStoreId')->willReturn($defaultStoreId); + $helperMock->expects($this->exactly(2))->method('setCurrentStore')->withConsecutive(array($magentoStoreId), array($defaultStoreId)); + + $helperMock->expects($this->once())->method('getImageUrlForSize')->with($imageSize, $productModelMock)->willReturn($imageUrl); + + $return = $helperMock->getImageUrlById($productId, $magentoStoreId); + + $this->assertEquals($return, $imageUrl); + } + + public function testGetImageUrlByIdDataProvider() + { + return array( + array(array('imageSize' => Ebizmarts_MailChimp_Model_Config::IMAGE_SIZE_DEFAULT, 'configImageSize' => Ebizmarts_MailChimp_Helper_Data::DEFAULT_SIZE)), + array(array('imageSize' => Ebizmarts_MailChimp_Model_Config::IMAGE_SIZE_SMALL, 'configImageSize' => Ebizmarts_MailChimp_Helper_Data::SMALL_SIZE)), + array(array('imageSize' => Ebizmarts_MailChimp_Model_Config::IMAGE_SIZE_THUMBNAIL, 'configImageSize' => Ebizmarts_MailChimp_Helper_Data::THUMBNAIL_SIZE)) + ); + } + public function testGetOriginalImageUrlById() + { + $productId = 1; + $magentoStoreId = 1; + $defaultStoreId = 0; + $imageSize = Ebizmarts_MailChimp_Model_Config::IMAGE_SIZE_DEFAULT; + $imageUrl = 'http://magento.com/catalog/product/image.jpg'; + $configImageSize = Ebizmarts_MailChimp_Helper_Data::ORIGINAL_SIZE; + + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('getProductResourceModel', 'getProductModel', 'getImageSize', 'getCurrentStoreId', + 'setCurrentStore', 'getImageUrl', 'getOriginalPath')) + ->getMock(); + + $productModelMock = $this->getMockBuilder(Mage_Catalog_Model_Product::class) + ->disableOriginalConstructor() + ->setMethods(array('setData', 'getImageUrl', 'getThumbnailUrl', 'getSmallImageUrl')) + ->getMock(); + + $productResourceModelMock = $this->getMockBuilder(Mage_Catalog_Model_Resource_Product::class) + ->disableOriginalConstructor() + ->setMethods(array('getAttributeRawValue')) + ->getMock(); + + $imageModelMock = $this->getMockBuilder(Mage_Media_Model_Image::class) + ->disableOriginalConstructor() + ->getMock(); + + $helperMock->expects($this->once())->method('getProductResourceModel')->willReturn($productResourceModelMock); + $helperMock->expects($this->once())->method('getProductModel')->willReturn($productModelMock); + $helperMock->expects($this->once())->method('getImageSize')->with($magentoStoreId)->willReturn($configImageSize); + + $productResourceModelMock->expects($this->once())->method('getAttributeRawValue')->with($productId, $imageSize, $magentoStoreId)->willReturn($imageModelMock); + + $productModelMock->expects($this->once())->method('setData')->with($imageSize, $imageModelMock); + + $helperMock->expects($this->once())->method('getCurrentStoreId')->willReturn($defaultStoreId); $helperMock->expects($this->exactly(2))->method('setCurrentStore')->withConsecutive(array($magentoStoreId), array($defaultStoreId)); - $helperMock->expects($this->once())->method('getImageFunctionName')->with($imageSize)->willReturn($upperCaseImage); + $helperMock->expects($this->once())->method('getOriginalPath')->with($imageModelMock)->willReturn($imageUrl); $return = $helperMock->getImageUrlById($productId, $magentoStoreId); - $this->assertEquals($return, 'ImageUrl'); + $this->assertEquals($return, $imageUrl); } public function testGetImageFunctionName() @@ -951,7 +1012,7 @@ public function testSaveLastItemsSent() array(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_PCD_LAST_ID, $promoCodeLastId), array(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_ENABLED, 1), array(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_RESEND_TURN, 1) - ); + ); $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) ->disableOriginalConstructor() @@ -1023,4 +1084,337 @@ public function testIsEcomSyncDataEnabledWithStoreIdNull() $this->assertEquals($expectedResult, $result); } + + public function testGetListInterestCategories() + { + $scopeId = 1; + $scope = 'stores'; + $listId = 'a1s2d3f4g5'; + $interestCategoryId = 1; + $categoriesResponse = array('categories' => array(array('id' => $interestCategoryId, 'title' => 'Category Title', 'type' => 'checkbox'))); + + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('getApi', 'getGeneralList')) + ->getMock(); + + $apiMock = $this->getMockBuilder(Ebizmarts_MailChimp::class) + ->disableOriginalConstructor() + ->setMethods(array('getLists')) + ->getMock(); + + $apiListsMock = $this->getMockBuilder(Ebizmarts_MailChimp::class) + ->disableOriginalConstructor() + ->setMethods(array('getInterestCategory')) + ->getMock(); + + $apiListsInterestCategoryMock = $this->getMockBuilder(MailChimp_ListsInterestCategory::class) + ->disableOriginalConstructor() + ->setMethods(array('getAll')) + ->getMock(); + + $helperMock->expects($this->once())->method('getApi')->with($scopeId, $scope)->willReturn($apiMock); + $helperMock->expects($this->once())->method('getGeneralList')->with($scopeId, $scope)->willReturn($listId); + + $apiMock->expects($this->once())->method('getLists')->willReturn($apiListsMock); + + $apiListsMock->expects($this->once())->method('getInterestCategory')->willReturn($apiListsInterestCategoryMock); + + $apiListsInterestCategoryMock->expects($this->once())->method('getAll')->with($listId, 'categories')->willReturn($categoriesResponse); + + $helperMock->getListInterestCategories($scopeId, $scope); + } + + public function testGetListInterestGroups() + { + $scopeId = 1; + $scope = 'stores'; + $listId = 'a1s2d3f4g5'; + $interestCategoryId = 1; + $categoriesResponse = array('categories' => array(array('id' => $interestCategoryId, 'title' => 'Category Title', 'type' => 'checkbox'))); + $interestsResponse = array('interests' => array(array('id' => 2, 'name' => 'Group Name'))); + + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('getApi', 'getGeneralList')) + ->getMock(); + + $apiMock = $this->getMockBuilder(Ebizmarts_MailChimp::class) + ->disableOriginalConstructor() + ->setMethods(array('getLists')) + ->getMock(); + + $apiListsMock = $this->getMockBuilder(Ebizmarts_MailChimp::class) + ->disableOriginalConstructor() + ->setMethods(array('getInterestCategory')) + ->getMock(); + + $apiListsInterestCategoryMock = $this->getMockBuilder(MailChimp_ListsInterestCategory::class) + ->disableOriginalConstructor() + ->setMethods(array('getAll', 'getInterests')) + ->getMock(); + + $apiListsInterestCategoryInterestsMock = $this->getMockBuilder(MailChimp_ListInterestCategoryInterests::class) + ->disableOriginalConstructor() + ->setMethods(array('getAll')) + ->getMock(); + + $helperMock->expects($this->once())->method('getApi')->with($scopeId, $scope)->willReturn($apiMock); + $helperMock->expects($this->once())->method('getGeneralList')->with($scopeId, $scope)->willReturn($listId); + + $apiMock->expects($this->once())->method('getLists')->willReturn($apiListsMock); + + $apiListsMock->expects($this->once())->method('getInterestCategory')->willReturn($apiListsInterestCategoryMock); + + $apiListsInterestCategoryMock->expects($this->once())->method('getAll')->with($listId, 'categories')->willReturn($categoriesResponse); + $apiListsInterestCategoryMock->expects($this->once())->method('getInterests')->willReturn($apiListsInterestCategoryInterestsMock); + + $apiListsInterestCategoryInterestsMock->expects($this->once())->method('getAll')->with($listId, $interestCategoryId)->willReturn($interestsResponse); + + $helperMock->getListInterestGroups($scopeId, $scope); + } + + public function testGetInterest() + { + $scopeId = 1; + $listId = 'a1s2d3f4g5'; + $interestIdOne = 'z0x9c8v7b6'; + $interestNameOne = 'Group One Name'; + $displayOrderOne = 1; + $interestIdTwo = 'p4o5i6u7y8'; + $interestNameTwo = 'Group Two Name'; + $displayOrderTwo = 2; + $localGroups = "$interestIdOne,$interestIdTwo"; + $interestCategoryId = 1; + $categoriesResponse = array('categories' => array(array('id' => $interestCategoryId, 'title' => 'Category Title', 'type' => 'checkbox'))); + $interestsResponseOne = array('interests' => array(array('category_id' => $interestCategoryId, 'id' => $interestIdOne, 'name' => $interestNameOne, 'display_order' => $displayOrderOne))); + $interestsResponseTwo = array('interests' => array(array('category_id' => $interestCategoryId, 'id' => $interestIdTwo, 'name' => $interestNameTwo, 'display_order' => $displayOrderTwo))); + $expectedResult = array(1 => array('category' => array($displayOrderOne => array('id' => $interestIdOne, 'name' => $interestNameOne, 'checked' => false), $displayOrderTwo => array('id' => $interestIdTwo, 'name' => $interestNameTwo, 'checked' => false)))); + + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('getApi', 'getGeneralList', 'getLocalInterestCategories')) + ->getMock(); + + $apiMock = $this->getMockBuilder(Ebizmarts_MailChimp::class) + ->disableOriginalConstructor() + ->setMethods(array('getLists')) + ->getMock(); + + $apiListsMock = $this->getMockBuilder(Ebizmarts_MailChimp::class) + ->disableOriginalConstructor() + ->setMethods(array('getInterestCategory')) + ->getMock(); + + $apiListsInterestCategoryMock = $this->getMockBuilder(MailChimp_ListsInterestCategory::class) + ->disableOriginalConstructor() + ->setMethods(array('getAll', 'getInterests')) + ->getMock(); + + $apiListsInterestCategoryInterestsMock = $this->getMockBuilder(MailChimp_ListInterestCategoryInterests::class) + ->disableOriginalConstructor() + ->setMethods(array('getAll')) + ->getMock(); + + $helperMock->expects($this->once())->method('getLocalInterestCategories')->with($scopeId)->willReturn($localGroups); + $helperMock->expects($this->once())->method('getApi')->with($scopeId)->willReturn($apiMock); + $helperMock->expects($this->once())->method('getGeneralList')->with($scopeId)->willReturn($listId); + + $apiMock->expects($this->once())->method('getLists')->willReturn($apiListsMock); + + $apiListsMock->expects($this->once())->method('getInterestCategory')->willReturn($apiListsInterestCategoryMock); + + $apiListsInterestCategoryMock->expects($this->once())->method('getAll')->with($listId)->willReturn($categoriesResponse); + + $apiListsInterestCategoryMock->expects($this->once())->method('getInterests')->willReturn($apiListsInterestCategoryInterestsMock); + + $apiListsInterestCategoryInterestsMock->expects($this->exactly(2))->method('getAll')->withConsecutive( + array($listId, $interestIdOne), + array($listId, $interestIdTwo) + )->willReturnOnConsecutiveCalls( + $interestsResponseOne, + $interestsResponseTwo + ); + + $result = $helperMock->getInterest($scopeId); + + $this->assertEquals($expectedResult, $result); + } + + public function testGetInterestGroups() + { + $customerId = 1; + $subscriberId = 1; + $storeId = 1; + $interestGroupId = 1; + $interestIdOne = 'z0x9c8v7b6'; + $interestNameOne = 'Group One Name'; + $displayOrderOne = 1; + $interestIdTwo = 'p4o5i6u7y8'; + $interestNameTwo = 'Group Two Name'; + $displayOrderTwo = 2; + $interest = array(1 => array('category' => array($displayOrderOne => array('id' => $interestIdOne, 'name' => $interestNameOne, 'checked' => false), $displayOrderTwo => array('id' => $interestIdTwo, 'name' => $interestNameTwo, 'checked' => false)))); + $encodedGroupData = '{"bc15dbe6a5":{"d6b7541ee7":"d6b7541ee7"},"2a2f23d671":"36c250eeff"}'; + $groupData = array( + 'bc15dbe6a5' => array('d6b7541ee7' => 'd6b7541ee7'), + '2a2f23d671' => '36c250eeff' + ); + $expectedResult = $interest; + + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('getInterest', 'getInterestGroupModel', 'getLocalInterestCategories', 'arrayDecode', 'isSubscriptionEnabled')) + ->getMock(); + + $interestGroupMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Interestgroup::class) + ->disableOriginalConstructor() + ->setMethods(array('getByRelatedIdStoreId', 'getId', 'getGroupdata')) + ->getMock(); + + $helperMock->expects($this->once())->method('isSubscriptionEnabled')->with($storeId)->willReturn(true); + $helperMock->expects($this->once())->method('getInterest')->with($storeId)->willReturn($interest); + $helperMock->expects($this->once())->method('getInterestGroupModel')->willReturn($interestGroupMock); + + $interestGroupMock->expects($this->once())->method('getByRelatedIdStoreId')->with($customerId, $subscriberId, $storeId)->willReturnSelf(); + $interestGroupMock->expects($this->once())->method('getId')->willReturn($interestGroupId); + $interestGroupMock->expects($this->once())->method('getGroupdata')->willReturn($encodedGroupData); + + $helperMock->expects($this->once())->method('arrayDecode')->with($encodedGroupData)->willReturn($groupData); + + $result = $helperMock->getInterestGroups($customerId, $subscriberId, $storeId); + + $this->assertEquals($expectedResult, $result); + } + + public function testGetInterestGroupsIsSubscriptionDisabled () + { + $customerId = 1; + $subscriberId = 1; + $storeId = 1; + $expectedResult = array(); + + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('isSubscriptionEnabled')) + ->getMock(); + + $helperMock->expects($this->once())->method('isSubscriptionEnabled')->with($storeId)->willReturn(false); + + $result = $helperMock->getInterestGroups($customerId, $subscriberId, $storeId); + + $this->assertEquals($expectedResult, $result); + } + + public function testSaveInterestGroupData() + { + $params = array(); + $customerId = 2; + $subscriberId = 2; + $origCustomerId = 1; + $origSubscriberId = 1; + $storeId = 1; + $encodedGroupData = '{"bc15dbe6a5":{"d6b7541ee7":"d6b7541ee7"},"2a2f23d671":"36c250eeff"}'; + $groupData = array( + 'bc15dbe6a5' => array('d6b7541ee7' => 'd6b7541ee7'), + '2a2f23d671' => '36c250eeff' + ); + $currentDateTime = '2018-07-26 12:43:40'; + + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('getInterestGroupsIfAvailable', 'isAdmin', 'getCustomerSession', 'getInterestGroupModel', + 'getCurrentDateTime', 'arrayEncode')) + ->getMock(); + + $interestGroupMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Interestgroup::class) + ->disableOriginalConstructor() + ->setMethods(array('getByRelatedIdStoreId', 'getSubscriberId', 'getCustomerId', 'setSubscriberId', + 'setCustomerId', 'setGroupdata', 'getGroupdata', 'setStoreId', 'setUpdatedAt', 'save')) + ->getMock(); + + $subscriberMock = $this->getMockBuilder(Mage_Newsletter_Model_Subscriber::class) + ->disableOriginalConstructor() + ->setMethods(array('getSubscriberId')) + ->getMock(); + + $customerSessionMock = $this->getMockBuilder(Mage_Customer_Model_Session::class) + ->disableOriginalConstructor() + ->setMethods(array('isLoggedIn', 'getCustomer')) + ->getMock(); + + $customerMock = $this->getMockBuilder(Mage_Customer_Model_Customer::class) + ->disableOriginalConstructor() + ->setMethods(array('getId')) + ->getMock(); + + $helperMock->expects($this->once())->method('getInterestGroupsIfAvailable')->with($params)->willReturn($groupData); + $helperMock->expects($this->once())->method('getCustomerSession')->willReturn($customerSessionMock); + $helperMock->expects($this->once())->method('isAdmin')->willReturn(false); + + $customerSessionMock->expects($this->once())->method('isLoggedIn')->willReturn(true); + $customerSessionMock->expects($this->once())->method('getCustomer')->willReturn($customerMock); + + $customerMock->expects($this->once())->method('getId')->willReturn($customerId); + + $subscriberMock->expects($this->once())->method('getSubscriberId')->willReturn($subscriberId); + + $helperMock->expects($this->once())->method('getInterestGroupModel')->willReturn($interestGroupMock); + + $interestGroupMock->expects($this->once())->method('getByRelatedIdStoreId')->with($customerId, $subscriberId, $storeId)->willReturnSelf(); + $interestGroupMock->expects($this->once())->method('getSubscriberId')->willReturn($origSubscriberId); + $interestGroupMock->expects($this->once())->method('getCustomerId')->willReturn($origCustomerId); + $interestGroupMock->expects($this->once())->method('setSubscriberId')->with($subscriberId)->willReturnSelf(); + $interestGroupMock->expects($this->once())->method('setCustomerId')->with($customerId)->willReturnSelf(); + + $helperMock->expects($this->once())->method('arrayEncode')->with($groupData)->willReturn($encodedGroupData); + + $interestGroupMock->expects($this->once())->method('setGroupdata')->with($encodedGroupData)->willReturnSelf(); + $interestGroupMock->expects($this->once())->method('getGroupdata')->willReturn($encodedGroupData); + $interestGroupMock->expects($this->once())->method('setStoreId')->with($storeId)->willReturnSelf(); + + $helperMock->expects($this->once())->method('getCurrentDateTime')->willReturn($currentDateTime); + + $interestGroupMock->expects($this->once())->method('setUpdatedAt')->with($currentDateTime)->willReturnSelf(); + $interestGroupMock->expects($this->once())->method('save')->willReturnSelf(); + + $helperMock->saveInterestGroupData($params, $storeId, null, $subscriberMock); + } + + public function testGetMCJs() + { + $storeId = 1; + $jsUrl = 'https://chimpstatic.com/mcjs-connected/js/users/1647ea7abc3f2f3259e2613f9/dffd1d29fea0323354a9caa32.js'; + + $expectedResult = ''; + + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('getMageApp', 'isEcomSyncDataEnabled', 'getConfigValueForScope', + 'areJsUrlAndListScopesEqual')) + ->getMock(); + + $mageAppMock = $this->getMockBuilder(Mage_Core_Model_App::class) + ->disableOriginalConstructor() + ->setMethods(array('getStore')) + ->getMock(); + + $storeMock = $this->getMockBuilder(Mage_Core_Model_Store::class) + ->disableOriginalConstructor() + ->setMethods(array('getId')) + ->getMock(); + + $helperMock->expects($this->once())->method('getMageApp')->willReturn($mageAppMock); + + $mageAppMock->expects($this->once())->method('getStore')->willReturn($storeMock); + + $storeMock->expects($this->once())->method('getId')->willReturn($storeId); + + $helperMock->expects($this->once())->method('isEcomSyncDataEnabled')->with($storeId)->willReturn(true); + $helperMock->expects($this->once())->method('getConfigValueForScope')->with(Ebizmarts_MailChimp_Model_Config::ECOMMERCE_MC_JS_URL, $storeId)->willReturn($jsUrl); + $helperMock->expects($this->once())->method('areJsUrlAndListScopesEqual')->with($storeId)->willReturn(true); + + $result = $helperMock->getMCJs(); + + $this->assertEquals($expectedResult, $result); + } } diff --git a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/BatchesTest.php b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/BatchesTest.php index af1dc0ece..f6999e1b3 100644 --- a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/BatchesTest.php +++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/BatchesTest.php @@ -252,7 +252,7 @@ public function handleEcommerceBatchesDataProvider(){ return array( array(array('mailchimp_api_status' => true, 'isEcomSyncDataEnabled' => 1, '_getResults' => 1, '_sendEcommerceBatch' => 1, 'handleResendDataAfter' => 1, 'addSyncValueToArray' => 1, 'getIterator' => 2, 'getId' => 2)), - array(array('mailchimp_api_status' => false, 'isEcomSyncDataEnabled' => 0, '_getResults' => 0, '_sendEcommerceBatch' => 0, 'handleResendDataAfter' => 0, 'addSyncValueToArray' => 0, + array(array('mailchimp_api_status' => false, 'isEcomSyncDataEnabled' => 1, '_getResults' => 0, '_sendEcommerceBatch' => 0, 'handleResendDataAfter' => 0, 'addSyncValueToArray' => 0, 'getIterator' => 1, 'getId' => 1)) ); } diff --git a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/CartsTest.php b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/CartsTest.php old mode 100644 new mode 100755 index 26692bc41..175219480 --- a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/CartsTest.php +++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/CartsTest.php @@ -1,16 +1,26 @@ cartsApiMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Api_Carts::class); } @@ -21,28 +31,1572 @@ public function tearDown() public function testCreateBatchJson() { - $mailchimpStoreId = 'a1s2d3f4g5h6j7k8l9n0'; - $magentoStoreId = 1; $batchArray = array(); - $cartsApiMock = $this->cartsApiMock->setMethods(array('getHelper', '_getConvertedQuotes', '_getModifiedQuotes', '_getNewQuotes')) + $cartsApiMock = $this->cartsApiMock->setMethods(array( + 'getHelper', + '_getConvertedQuotes', + '_getModifiedQuotes', + '_getNewQuotes', + 'setBatchId' + )) ->getMock(); - $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) ->disableOriginalConstructor() ->setMethods(array('isAbandonedCartEnabled', 'getAbandonedCartFirstDate', 'getDateMicrotime', 'getResendTurn')) ->getMock(); + $cartsApiMock->expects($this->once())->method('setBatchId')->with(self::BATCH_ID); + $cartsApiMock->expects($this->once())->method('getHelper')->willReturn($helperMock); + $cartsApiMock->expects($this->once())->method('_getConvertedQuotes')->with(self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID)->willReturn($batchArray); + $cartsApiMock->expects($this->once())->method('_getModifiedQuotes')->with(self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID)->willReturn($batchArray); + $cartsApiMock->expects($this->once())->method('_getNewQuotes')->with(self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID)->willReturn($batchArray); + $helperMock->expects($this->once())->method('isAbandonedCartEnabled')->with(self::MAGENTO_STORE_ID)->willReturn(true); + $helperMock->expects($this->once())->method('getAbandonedCartFirstDate')->with(self::MAGENTO_STORE_ID)->willReturn('00-00-00 00:00:00'); + $helperMock->expects($this->once())->method('getDateMicrotime')->willReturn(self::DATE); + $helperMock->expects($this->once())->method('getResendTurn')->with(self::MAGENTO_STORE_ID)->willReturn(null); + + $cartsApiMock->createBatchJson(self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID); + } + + public function testCreateBatchJsonisAbandonedCartDisabled() + { + $cartsApiMock = $this->cartsApiMock + ->setMethods(array('getHelper')) + ->getMock(); + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('isAbandonedCartEnabled')) + ->getMock(); + $cartsApiMock->expects($this->once())->method('getHelper')->willReturn($helperMock); - $cartsApiMock->expects($this->once())->method('_getConvertedQuotes')->with($mailchimpStoreId, $magentoStoreId)->willReturn($batchArray); - $cartsApiMock->expects($this->once())->method('_getModifiedQuotes')->with($mailchimpStoreId, $magentoStoreId)->willReturn($batchArray); - $cartsApiMock->expects($this->once())->method('_getNewQuotes')->with($mailchimpStoreId, $magentoStoreId)->willReturn($batchArray); + $helperMock->expects($this->once())->method('isAbandonedCartEnabled')->with(self::MAGENTO_STORE_ID)->willReturn(false); + + $cartsApiMock->createBatchJson(self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID); + } + + public function testGetConvertedQuotes () + { + $mailchimpTableName = 'mailchimp_ecommerce_sync_data'; + $arrayAddFieldToFilter = array('eq' => 0); + $arrayAddFieldToFilterStoreId = array('eq' => self::MAGENTO_STORE_ID); + $where = "m4m.mailchimp_sync_deleted = 0"; + $arrayTableName = array('m4m' => $mailchimpTableName); + $conditionSelect = "m4m.related_id = main_table.entity_id and m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_QUOTE . "' + AND m4m.mailchimp_store_id = '" . self::MAILCHIMP_STORE_ID . "'"; + $m4m = array('m4m.*'); + + $cartsApiMock = $this->cartsApiMock->setMethods(array( + 'getMailchimpEcommerceDataTableName', + 'getQuoteCollection', + 'getBatchLimitFromConfig', + 'getAllCartsByEmail', + 'getCounter', + 'getBatchId', + '_updateSyncData', + 'setCounter' + )) + ->getMock(); + $quoteResoureceCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Quote_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('addFieldToFilter', 'getSelect', 'getIterator')) + ->getMock(); + $varienSelectMock = $this + ->getMockBuilder(Varien_Db_Select::class) + ->disableOriginalConstructor() + ->setMethods(array('joinLeft', 'where', 'limit')) + ->getMock(); + $cartModelMock = $this + ->getMockBuilder(Mage_Sales_Model_Quote::class) + ->disableOriginalConstructor() + ->setMethods(array('getEntityId', 'getCustomerEmail')) + ->getMock(); + $quoteByEmailResoureceCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Quote_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('clear', 'getIterator')) + ->getMock(); + $cartByEmailModelMock = $this + ->getMockBuilder(Mage_Sales_Model_Quote::class) + ->disableOriginalConstructor() + ->setMethods(array('getEntityId')) + ->getMock(); + + $cartsApiMock->expects($this->once()) + ->method('getMailchimpEcommerceDataTableName') + ->willReturn($mailchimpTableName); + $cartsApiMock->expects($this->once()) + ->method('getQuoteCollection') + ->willReturn($quoteResoureceCollectionMock); + $cartsApiMock->expects($this->once()) + ->method('getBatchLimitFromConfig') + ->willReturn(self::BATCH_LIMIT_FROM_CONFIG); + $cartsApiMock->expects($this->once()) + ->method('getAllCartsByEmail') + ->with(self::CUSTOMER_EMAIL_BY_CART, self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID) + ->willReturn($quoteByEmailResoureceCollectionMock); + $cartsApiMock->expects($this->exactly(4)) + ->method('getCounter') + ->willReturnOnConsecutiveCalls( + self::COUNTER, + self::COUNTER, + self::COUNTER, + self::COUNTER + ); + $cartsApiMock->expects($this->once()) + ->method('getBatchId') + ->willReturn(self::BATCH_ID); + $cartsApiMock->expects($this->exactly(2)) + ->method('_updateSyncData') + ->withConsecutive( + array(self::ALREADY_SENT_CART_ID, self::MAILCHIMP_STORE_ID, null, null, null, null, 1), + array(self::CART_ID, self::MAILCHIMP_STORE_ID, null, null, null, null, 1) + ); + $cartsApiMock->expects($this->exactly(2)) + ->method('setCounter') + ->withConsecutive( + array(self::COUNTER + 1), + array(self::COUNTER + 1) + ); + $quoteResoureceCollectionMock->expects($this->exactly(2)) + ->method('addFieldToFilter') + ->withConsecutive( + array(self::STRING_STORE_ID, $arrayAddFieldToFilterStoreId), + array(self::STRING_IS_ACTIVE, $arrayAddFieldToFilter) + ); + $quoteResoureceCollectionMock->expects($this->exactly(3)) + ->method('getSelect') + ->willReturnOnConsecutiveCalls( + $varienSelectMock, + $varienSelectMock, + $varienSelectMock + ); + $quoteResoureceCollectionMock->expects($this->once()) + ->method('getIterator') + ->willReturn(new ArrayIterator(array($cartModelMock))); + $varienSelectMock->expects($this->once()) + ->method('joinLeft') + ->with($arrayTableName, $conditionSelect, $m4m); + $varienSelectMock->expects($this->once()) + ->method('where') + ->with($where); + $varienSelectMock->expects($this->once()) + ->method('limit') + ->with(self::BATCH_LIMIT_FROM_CONFIG); + $cartModelMock->expects($this->once()) + ->method('getCustomerEmail') + ->willReturnOnConsecutiveCalls(self::CUSTOMER_EMAIL_BY_CART); + $cartModelMock->expects($this->once()) + ->method('getEntityId') + ->willReturn(self::CART_ID); + $quoteByEmailResoureceCollectionMock->expects($this->once()) + ->method('clear'); + $quoteByEmailResoureceCollectionMock->expects($this->once()) + ->method('getIterator') + ->willReturn(new ArrayIterator(array($cartByEmailModelMock))); + $cartByEmailModelMock->expects($this->once()) + ->method('getEntityId') + ->willReturn(self::ALREADY_SENT_CART_ID); + + $cartsApiMock->_getConvertedQuotes(self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID); + } + + public function testGetModifiedQuotes() + { + $mcTableName = 'mailchimp_ecommerce_sync_data'; + $customerEmailAddress = ''; + $cartJson = '{"id":"692","customer":{"id":"GUEST-2018-11-30-20-00-07-96938700","email_address":"test@ebizmarts.com","opt_in_status":false,"first_name":"Lucia","last_name":"en el checkout","address":{"address1":"asdf","city":"asd","postal_code":"212312","country":"Tajikistan","country_code":"TJ"}},"campaign_id":"482d28ee12","checkout_url":"http:\/\/f3364930.ngrok.io\/mailchimp\/cart\/loadquote\?id=692&token=ec4f79b2e4677d2edc5bf78c934e5794","currency_code":"USD","order_total":"1700.0000","tax_total":0,"lines":[{"id":"1","product_id":"425","product_variant_id":"310","quantity":5,"price":"1700.0000"}]}'; + $customerId = 1; + $arrayAddFieldToFilter = array('eq' => 1); + $arrayAddFieldToFilterStoreId = array('eq' => self::MAGENTO_STORE_ID); + $where = "m4m.mailchimp_sync_deleted = 0 + AND m4m.mailchimp_sync_delta < updated_at"; + $arrayTableName = array('m4m' => $mcTableName); + $conditionSelect = "m4m.related_id = main_table.entity_id and m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_QUOTE . "' + AND m4m.mailchimp_store_id = '" . self::MAILCHIMP_STORE_ID . "'"; + $m4m = array('m4m.*'); + $allCarts = array(array('method' => 'DELETE', 'path' => '/ecommerce/stores/'.self::MAILCHIMP_STORE_ID.'/carts/'. self::ALREADY_SENT_CART_ID, 'operation_id' => self::BATCH_ID . '_' . self::ALREADY_SENT_CART_ID, 'body' => '')); + $token = 'ec4f79b2e4677d2edc5bf78c934e5794'; + + $cartsApiMock = $this->cartsApiMock->setMethods( + array( + 'setToken', + 'getToken', + 'getBatchId', + 'getMailchimpEcommerceDataTableName', + 'getBatchLimitFromConfig', + '_updateSyncData', + 'getQuoteCollection', + 'getCustomerModel', + 'getWebSiteIdFromMagentoStoreId', + 'setCounter', + 'getCounter', + '_makeCart', + 'getAllCartsByEmail', + 'addProductNotSentData' + )) + ->getMock(); + $cartModelMock = $this + ->getMockBuilder(Mage_Sales_Model_Quote::class) + ->disableOriginalConstructor() + ->setMethods(array('getEntityId', 'getCustomerEmail', 'getCustomerId')) + ->getMock(); + $quoteResoureceCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Quote_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('addFieldToFilter', 'getSelect', 'getIterator')) + ->getMock(); + $varienSelectMock = $this + ->getMockBuilder(Varien_Db_Select::class) + ->disableOriginalConstructor() + ->setMethods(array('joinLeft', 'where', 'limit')) + ->getMock(); + $customerModelMock = $this + ->getMockBuilder(Mage_Customer_Model_Customer::class) + ->disableOriginalConstructor() + ->setMethods(array('setWebsiteId', 'loadByEmail', 'getEmail')) + ->getMock(); + $quoteByEmailResoureceCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Quote_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('clear', 'getIterator')) + ->getMock(); + $cartByEmailModelMock = $this + ->getMockBuilder(Mage_Sales_Model_Quote::class) + ->disableOriginalConstructor() + ->setMethods(array('getEntityId')) + ->getMock(); + + $cartsApiMock->expects($this->once()) + ->method('getToken') + ->willReturn($token); + $cartsApiMock->expects($this->once()) + ->method('setToken') + ->with(null); + $cartsApiMock->expects($this->once()) + ->method('getBatchId') + ->willReturn(self::BATCH_ID); + $cartsApiMock->expects($this->once()) + ->method('getMailchimpEcommerceDataTableName') + ->willReturn($mcTableName); + $cartsApiMock->expects($this->once()) + ->method('getQuoteCollection') + ->willReturn($quoteResoureceCollectionMock); + $cartsApiMock->expects($this->once()) + ->method('getBatchLimitFromConfig') + ->willReturn(self::BATCH_LIMIT_FROM_CONFIG); + $cartsApiMock->expects($this->once()) + ->method('getCustomerModel') + ->willReturn($customerModelMock); + $cartsApiMock->expects($this->once()) + ->method('getWebSiteIdFromMagentoStoreId') + ->with(self::MAGENTO_STORE_ID) + ->willReturn(self::WEB_SITE_ID_FROM_MAGENTO_STORE_ID); + $cartsApiMock->expects($this->once()) + ->method('getAllCartsByEmail') + ->with(self::CUSTOMER_EMAIL_BY_CART,self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID) + ->willReturn($quoteByEmailResoureceCollectionMock); + $cartsApiMock->expects($this->exactly(4)) + ->method('getCounter') + ->willReturnOnConsecutiveCalls( + self::COUNTER, + self::COUNTER, + self::COUNTER, + self::COUNTER + ); + $cartsApiMock->expects($this->exactly(2)) + ->method('_updateSyncData') + ->withConsecutive( + array(self::ALREADY_SENT_CART_ID, self::MAILCHIMP_STORE_ID, null, null, null, null, 1), + array(self::CART_ID, self::MAILCHIMP_STORE_ID, null, null, null, null, null, $token) + ); + $cartsApiMock->expects($this->exactly(2)) + ->method('setCounter') + ->withConsecutive( + array(self::COUNTER + 1), + array(self::COUNTER + 1) + ); + $cartsApiMock->expects($this->once()) + ->method('_makeCart') + ->with($cartModelMock, self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID, true) + ->willReturn($cartJson); + $cartsApiMock->expects($this->once()) + ->method('addProductNotSentData') + ->with(self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID, $cartModelMock, $allCarts) + ->willReturn($allCarts); + $cartModelMock->expects($this->exactly(3)) + ->method('getCustomerEmail') + ->willReturnOnConsecutiveCalls( + self::CUSTOMER_EMAIL_BY_CART, + self::CUSTOMER_EMAIL_BY_CART, + self::CUSTOMER_EMAIL_BY_CART + ); + $cartModelMock->expects($this->once()) + ->method('getEntityId') + ->willReturn(self::CART_ID); + $cartModelMock->expects($this->once()) + ->method('getCustomerId') + ->willReturn($customerId); + $quoteResoureceCollectionMock->expects($this->exactly(2)) + ->method('addFieldToFilter') + ->withConsecutive( + array(self::STRING_IS_ACTIVE, $arrayAddFieldToFilter), + array(self::STRING_STORE_ID, $arrayAddFieldToFilterStoreId) + ); + $quoteResoureceCollectionMock->expects($this->exactly(3)) + ->method('getSelect') + ->willReturnOnConsecutiveCalls( + $varienSelectMock, + $varienSelectMock, + $varienSelectMock + ); + $quoteResoureceCollectionMock->expects($this->once()) + ->method('getIterator') + ->willReturn(new ArrayIterator(array($cartModelMock))); + $varienSelectMock->expects($this->once()) + ->method('joinLeft') + ->with($arrayTableName, $conditionSelect, $m4m); + $varienSelectMock->expects($this->once()) + ->method('where') + ->with($where); + $varienSelectMock->expects($this->once()) + ->method('limit') + ->with(self::BATCH_LIMIT_FROM_CONFIG); + $customerModelMock->expects($this->once()) + ->method('setWebsiteId') + ->with(self::WEB_SITE_ID_FROM_MAGENTO_STORE_ID); + $customerModelMock->expects($this->once()) + ->method('loadByEmail') + ->with(self::CUSTOMER_EMAIL_BY_CART); + $customerModelMock->expects($this->once()) + ->method('getEmail') + ->willReturn($customerEmailAddress); + $quoteByEmailResoureceCollectionMock->expects($this->once()) + ->method('clear'); + $quoteByEmailResoureceCollectionMock->expects($this->once()) + ->method('getIterator') + ->willReturn(new ArrayIterator(array($cartByEmailModelMock))); + $cartByEmailModelMock->expects($this->once()) + ->method('getEntityId') + ->willReturn(self::ALREADY_SENT_CART_ID); + + $cartsApiMock->_getModifiedQuotes(self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID); + } + + public function testGetModifiedQuotesGuestCustomer() + { + $mcTableName = 'mailchimp_ecommerce_sync_data'; + $customerId = ''; + $customerEmailAddress = 'test@ebizmarts.com'; + $stringStoreId = 'store_id'; + $arrayAddFieldToFilter = array('eq' => 1); + $arrayAddFieldToFilterStoreId = array('eq' => self::MAGENTO_STORE_ID); + $where = "m4m.mailchimp_sync_deleted = 0 + AND m4m.mailchimp_sync_delta < updated_at"; + $arrayTableName = array('m4m' => $mcTableName); + $conditionSelect = "m4m.related_id = main_table.entity_id and m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_QUOTE . "' + AND m4m.mailchimp_store_id = '" . self::MAILCHIMP_STORE_ID . "'"; + $m4m = array('m4m.*'); + + $cartsApiMock = $this->cartsApiMock->setMethods( + array( + 'getQuoteCollection', + 'getBatchLimitFromConfig', + '_updateSyncData', + 'getCustomerModel', + 'getWebSiteIdFromMagentoStoreId', + 'getBatchId', + 'getOrderCollection', + 'getMailchimpEcommerceDataTableName' + )) + ->getMock(); + $newCartsCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Quote_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('addFieldToFilter', 'getSelect', 'getIterator')) + ->getMock(); + $varienSelectMock = $this + ->getMockBuilder(Varien_Db_Select::class) + ->disableOriginalConstructor() + ->setMethods(array('where', 'limit', 'joinLeft')) + ->getMock(); + $customerModelMock = $this + ->getMockBuilder(Mage_Customer_Model_Customer::class) + ->disableOriginalConstructor() + ->setMethods(array('setWebsiteId', 'loadByEmail', 'getEmail')) + ->getMock(); + $cartModelMock = $this + ->getMockBuilder(Mage_Sales_Model_Quote::class) + ->disableOriginalConstructor() + ->setMethods(array('getEntityId', 'getCustomerEmail', 'getCustomerId')) + ->getMock(); + + $cartsApiMock->expects($this->once()) + ->method('getQuoteCollection') + ->willReturn($newCartsCollectionMock); + $cartsApiMock->expects($this->once()) + ->method('getBatchLimitFromConfig') + ->willReturn(self::BATCH_LIMIT_FROM_CONFIG); + $cartsApiMock->expects($this->once()) + ->method('_updateSyncData') + ->with(self::CART_ID, self::MAILCHIMP_STORE_ID); + $cartsApiMock->expects($this->once()) + ->method('getCustomerModel') + ->willReturn($customerModelMock); + $cartsApiMock->expects($this->once()) + ->method('getWebSiteIdFromMagentoStoreId') + ->with(self::MAGENTO_STORE_ID) + ->willReturn(self::WEB_SITE_ID_FROM_MAGENTO_STORE_ID); + $cartsApiMock->expects($this->once()) + ->method('getBatchId') + ->willReturn(self::BATCH_ID); + $cartsApiMock->expects($this->once()) + ->method('getMailchimpEcommerceDataTableName') + ->willReturn($mcTableName); + $newCartsCollectionMock->expects($this->exactly(2)) + ->method('addFieldToFilter') + ->withConsecutive( + array(self::STRING_IS_ACTIVE, $arrayAddFieldToFilter), + array($stringStoreId, $arrayAddFieldToFilterStoreId) + ); + $newCartsCollectionMock->expects($this->exactly(3)) + ->method('getSelect') + ->willReturnOnConsecutiveCalls( + $varienSelectMock, + $varienSelectMock, + $varienSelectMock + ); + $newCartsCollectionMock->expects($this->once()) + ->method('getIterator') + ->willReturn(new ArrayIterator(array($cartModelMock))); + $varienSelectMock->expects($this->once()) + ->method('where') + ->with($where); + $varienSelectMock->expects($this->once()) + ->method('limit') + ->with(self::BATCH_LIMIT_FROM_CONFIG); + $varienSelectMock->expects($this->once()) + ->method('joinLeft') + ->with($arrayTableName, $conditionSelect, $m4m); + $customerModelMock->expects($this->once()) + ->method('setWebsiteId') + ->with(self::WEB_SITE_ID_FROM_MAGENTO_STORE_ID); + $customerModelMock->expects($this->once()) + ->method('loadByEmail') + ->with(self::CUSTOMER_EMAIL_BY_CART); + $customerModelMock->expects($this->exactly(2)) + ->method('getEmail') + ->willReturnOnConsecutiveCalls( + $customerEmailAddress, + $customerEmailAddress + ); + $cartModelMock->expects($this->exactly(3)) + ->method('getCustomerEmail') + ->willReturnOnConsecutiveCalls( + self::CUSTOMER_EMAIL_BY_CART, + self::CUSTOMER_EMAIL_BY_CART, + self::CUSTOMER_EMAIL_BY_CART + ); + $cartModelMock->expects($this->once()) + ->method('getEntityId') + ->willReturn(self::CART_ID); + $cartModelMock->expects($this->once()) + ->method('getCustomerId') + ->willReturn($customerId); + + $cartsApiMock->_getModifiedQuotes(self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID); + } + + public function testGetModifiedQuotesEmptyJson() + { + $mcTableName = 'mailchimp_ecommerce_sync_data'; + $customerEmailAddress = ''; + $cartJson = ''; + $customerId = 1; + $arrayAddFieldToFilter = array('eq' => 1); + $arrayAddFieldToFilterStoreId = array('eq' => self::MAGENTO_STORE_ID); + $where = "m4m.mailchimp_sync_deleted = 0 + AND m4m.mailchimp_sync_delta < updated_at"; + $arrayTableName = array('m4m' => $mcTableName); + $conditionSelect = "m4m.related_id = main_table.entity_id and m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_QUOTE . "' + AND m4m.mailchimp_store_id = '" . self::MAILCHIMP_STORE_ID . "'"; + $m4m = array('m4m.*'); + $allCarts = array(array('method' => 'DELETE', 'path' => '/ecommerce/stores/'.self::MAILCHIMP_STORE_ID.'/carts/'. self::ALREADY_SENT_CART_ID, 'operation_id' => self::BATCH_ID . '_' . self::ALREADY_SENT_CART_ID, 'body' => '')); + + $cartsApiMock = $this->cartsApiMock->setMethods( + array( + 'setToken', + 'getBatchId', + 'getMailchimpEcommerceDataTableName', + 'getBatchLimitFromConfig', + '_updateSyncData', + 'getQuoteCollection', + 'getCustomerModel', + 'getWebSiteIdFromMagentoStoreId', + 'setCounter', + 'getCounter', + '_makeCart', + 'getAllCartsByEmail', + 'addProductNotSentData' + )) + ->getMock(); + $cartModelMock = $this + ->getMockBuilder(Mage_Sales_Model_Quote::class) + ->disableOriginalConstructor() + ->setMethods(array('getEntityId', 'getCustomerEmail', 'getCustomerId')) + ->getMock(); + $quoteResoureceCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Quote_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('addFieldToFilter', 'getSelect', 'getIterator')) + ->getMock(); + $varienSelectMock = $this + ->getMockBuilder(Varien_Db_Select::class) + ->disableOriginalConstructor() + ->setMethods(array('joinLeft', 'where', 'limit')) + ->getMock(); + $customerModelMock = $this + ->getMockBuilder(Mage_Customer_Model_Customer::class) + ->disableOriginalConstructor() + ->setMethods(array('setWebsiteId', 'loadByEmail', 'getEmail')) + ->getMock(); + $quoteByEmailResoureceCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Quote_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('clear', 'getIterator')) + ->getMock(); + $cartByEmailModelMock = $this + ->getMockBuilder(Mage_Sales_Model_Quote::class) + ->disableOriginalConstructor() + ->setMethods(array('getEntityId')) + ->getMock(); + + $cartsApiMock->expects($this->once()) + ->method('setToken') + ->with(null); + $cartsApiMock->expects($this->once()) + ->method('getBatchId') + ->willReturn(self::BATCH_ID); + $cartsApiMock->expects($this->once()) + ->method('getMailchimpEcommerceDataTableName') + ->willReturn($mcTableName); + $cartsApiMock->expects($this->once()) + ->method('getQuoteCollection') + ->willReturn($quoteResoureceCollectionMock); + $cartsApiMock->expects($this->once()) + ->method('getBatchLimitFromConfig') + ->willReturn(self::BATCH_LIMIT_FROM_CONFIG); + $cartsApiMock->expects($this->once()) + ->method('getCustomerModel') + ->willReturn($customerModelMock); + $cartsApiMock->expects($this->once()) + ->method('getWebSiteIdFromMagentoStoreId') + ->with(self::MAGENTO_STORE_ID) + ->willReturn(self::WEB_SITE_ID_FROM_MAGENTO_STORE_ID); + $cartsApiMock->expects($this->once()) + ->method('getAllCartsByEmail') + ->with(self::CUSTOMER_EMAIL_BY_CART,self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID) + ->willReturn($quoteByEmailResoureceCollectionMock); + $cartsApiMock->expects($this->exactly(2)) + ->method('getCounter') + ->willReturnOnConsecutiveCalls( + self::COUNTER, + self::COUNTER + ); + $cartsApiMock->expects($this->exactly(2)) + ->method('_updateSyncData') + ->withConsecutive( + array(self::ALREADY_SENT_CART_ID, self::MAILCHIMP_STORE_ID, null, null, null, null, 1), + array(self::CART_ID, self::MAILCHIMP_STORE_ID) + ); + $cartsApiMock->expects($this->once()) + ->method('setCounter') + ->with(self::COUNTER + 1); + $cartsApiMock->expects($this->once()) + ->method('_makeCart') + ->with($cartModelMock, self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID, true) + ->willReturn($cartJson); + $cartsApiMock->expects($this->once()) + ->method('addProductNotSentData') + ->with(self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID, $cartModelMock, $allCarts) + ->willReturn($allCarts); + $cartModelMock->expects($this->exactly(3)) + ->method('getCustomerEmail') + ->willReturnOnConsecutiveCalls( + self::CUSTOMER_EMAIL_BY_CART, + self::CUSTOMER_EMAIL_BY_CART, + self::CUSTOMER_EMAIL_BY_CART + ); + $cartModelMock->expects($this->once()) + ->method('getEntityId') + ->willReturn(self::CART_ID); + $cartModelMock->expects($this->once()) + ->method('getCustomerId') + ->willReturn($customerId); + $quoteResoureceCollectionMock->expects($this->exactly(2)) + ->method('addFieldToFilter') + ->withConsecutive( + array(self::STRING_IS_ACTIVE, $arrayAddFieldToFilter), + array(self::STRING_STORE_ID, $arrayAddFieldToFilterStoreId) + ); + $quoteResoureceCollectionMock->expects($this->exactly(3)) + ->method('getSelect') + ->willReturnOnConsecutiveCalls( + $varienSelectMock, + $varienSelectMock, + $varienSelectMock + ); + $quoteResoureceCollectionMock->expects($this->once()) + ->method('getIterator') + ->willReturn(new ArrayIterator(array($cartModelMock))); + $varienSelectMock->expects($this->once()) + ->method('joinLeft') + ->with($arrayTableName, $conditionSelect, $m4m); + $varienSelectMock->expects($this->once()) + ->method('where') + ->with($where); + $varienSelectMock->expects($this->once()) + ->method('limit') + ->with(self::BATCH_LIMIT_FROM_CONFIG); + $customerModelMock->expects($this->once()) + ->method('setWebsiteId') + ->with(self::WEB_SITE_ID_FROM_MAGENTO_STORE_ID); + $customerModelMock->expects($this->once()) + ->method('loadByEmail') + ->with(self::CUSTOMER_EMAIL_BY_CART); + $customerModelMock->expects($this->once()) + ->method('getEmail') + ->willReturn($customerEmailAddress); + $quoteByEmailResoureceCollectionMock->expects($this->once()) + ->method('clear'); + $quoteByEmailResoureceCollectionMock->expects($this->once()) + ->method('getIterator') + ->willReturn(new ArrayIterator(array($cartByEmailModelMock))); + $cartByEmailModelMock->expects($this->once()) + ->method('getEntityId') + ->willReturn(self::ALREADY_SENT_CART_ID); + + $cartsApiMock->_getModifiedQuotes(self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID); + } + + public function testGetNewQuotesNewQuote() + { + $existFirstDate = '2018-11-30'; + $customerId = 1; + $token = 'ec4f79b2e4677d2edc5bf78c934e5794'; + $customerEmailAddress = ''; + $allCarts = array(array('method' => 'DELETE', 'path' => '/ecommerce/stores/'.self::MAILCHIMP_STORE_ID.'/carts/'. self::ALREADY_SENT_CART_ID, 'operation_id' => self::BATCH_ID . '_' . self::ALREADY_SENT_CART_ID, 'body' => '')); + $cartJson = '{"id":"692","customer":{"id":"GUEST-2018-11-30-20-00-07-96938700","email_address":"test@ebizmarts.com","opt_in_status":false,"first_name":"Lucia","last_name":"en el checkout","address":{"address1":"asdf","city":"asd","postal_code":"212312","country":"Tajikistan","country_code":"TJ"}},"campaign_id":"482d28ee12","checkout_url":"http:\/\/f3364930.ngrok.io\/mailchimp\/cart\/loadquote\?id=692&token=ec4f79b2e4677d2edc5bf78c934e5794","currency_code":"USD","order_total":"1700.0000","tax_total":0,"lines":[{"id":"1","product_id":"425","product_variant_id":"310","quantity":5,"price":"1700.0000"}]}'; + $stringCustomerEmail = 'customer_email'; + $stringItemsCount = 'items_count'; + $stringUpdatedAt = 'updated_at'; + $arrayAddFieldToFilterUpdatedAt = array('gt' => $existFirstDate); + $arrayAddFieldToFilterItemsCount = array('gt' => 0); + $arrayAddFieldToFilterCustomerEmail = array('notnull' => true); + $arrayAddFieldToFilter = array('eq' => 1); + $arrayAddFieldToFilterStoreId = array('eq' => self::MAGENTO_STORE_ID); + $where = "m4m.mailchimp_sync_delta IS NULL"; + $allVisbleItems = array('item'); + $sizeOrderCollection = 0; + $addFieldToFilterOrderCollection = array('eq' => self::CUSTOMER_EMAIL_BY_CART); + $stringCustomerEmailMainTable = 'main_table.customer_email'; + $stringUpdated = 'main_table.updated_at'; + $addFieldToFilterUpdated = array('from' => ''); + + $cartsApiMock = $this->cartsApiMock->setMethods( + array( + 'getHelper', + 'getQuoteCollection', + 'getFirstDate', + 'joinMailchimpSyncDataWithoutWhere', + 'getBatchLimitFromConfig', + '_updateSyncData', + 'getCustomerModel', + 'getWebSiteIdFromMagentoStoreId', + 'getAllCartsByEmail', + 'getCounter', + 'getBatchId', + 'setCounter', + 'addProductNotSentData', + '_makeCart', + 'setToken', + 'getToken', + 'getOrderCollection' + )) + ->getMock(); + $helperMock = $this + ->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->setMethods(array('addResendFilter')) + ->getMock(); + $newCartsCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Quote_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('addFieldToFilter', 'getSelect', 'getIterator')) + ->getMock(); + $varienSelectMock = $this + ->getMockBuilder(Varien_Db_Select::class) + ->disableOriginalConstructor() + ->setMethods(array('where', 'limit')) + ->getMock(); + $customerModelMock = $this + ->getMockBuilder(Mage_Customer_Model_Customer::class) + ->disableOriginalConstructor() + ->setMethods(array('setWebsiteId', 'loadByEmail', 'getEmail')) + ->getMock(); + $quoteByEmailResoureceCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Quote_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('clear', 'getIterator')) + ->getMock(); + $cartModelMock = $this + ->getMockBuilder(Mage_Sales_Model_Quote::class) + ->disableOriginalConstructor() + ->setMethods(array('getEntityId', 'getCustomerEmail', 'getCustomerId', 'getAllVisibleItems')) + ->getMock(); + $cartByEmailModelMock = $this + ->getMockBuilder(Mage_Sales_Model_Quote::class) + ->disableOriginalConstructor() + ->setMethods(array('getEntityId')) + ->getMock(); + $orderCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Order_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('getSize', 'addFieldToFilter')) + ->getMock(); + + $cartsApiMock->expects($this->once()) + ->method('getHelper') + ->willReturn($helperMock); + $cartsApiMock->expects($this->once()) + ->method('getQuoteCollection') + ->willReturn($newCartsCollectionMock); + $cartsApiMock->expects($this->exactly(2)) + ->method('getFirstDate') + ->willReturnOnConsecutiveCalls( + $existFirstDate, + $existFirstDate + ); + $cartsApiMock->expects($this->once()) + ->method('joinMailchimpSyncDataWithoutWhere') + ->with($newCartsCollectionMock, self::MAILCHIMP_STORE_ID); + $cartsApiMock->expects($this->once()) + ->method('getBatchLimitFromConfig') + ->willReturn(self::BATCH_LIMIT_FROM_CONFIG); + $cartsApiMock->expects($this->exactly(2)) + ->method('_updateSyncData') + ->withConsecutive( + array(self::ALREADY_SENT_CART_ID, self::MAILCHIMP_STORE_ID, null, null, null, null, 1), + array(self::CART_ID, self::MAILCHIMP_STORE_ID, null, null, null, null, null, $token) + ); + $cartsApiMock->expects($this->once()) + ->method('getCustomerModel') + ->willReturn($customerModelMock); + $cartsApiMock->expects($this->once()) + ->method('getWebSiteIdFromMagentoStoreId') + ->with(self::MAGENTO_STORE_ID) + ->willReturn(self::WEB_SITE_ID_FROM_MAGENTO_STORE_ID); + $cartsApiMock->expects($this->once()) + ->method('getAllCartsByEmail') + ->with(self::CUSTOMER_EMAIL_BY_CART,self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID) + ->willReturn($quoteByEmailResoureceCollectionMock); + $cartsApiMock->expects($this->exactly(4)) + ->method('getCounter') + ->willReturnOnConsecutiveCalls( + self::COUNTER, + self::COUNTER, + self::COUNTER, + self::COUNTER + ); + $cartsApiMock->expects($this->once()) + ->method('getBatchId') + ->willReturn(self::BATCH_ID); + $cartsApiMock->expects($this->exactly(2)) + ->method('setCounter') + ->withConsecutive( + array(self::COUNTER + 1), + array(self::COUNTER + 1) + ); + $cartsApiMock->expects($this->once()) + ->method('addProductNotSentData') + ->with(self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID, $cartModelMock, $allCarts) + ->willReturn($allCarts); + $cartsApiMock->expects($this->once()) + ->method('_makeCart') + ->with($cartModelMock, self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID) + ->willReturn($cartJson); + $cartsApiMock->expects($this->once()) + ->method('getToken') + ->willReturn($token); + $cartsApiMock->expects($this->once()) + ->method('setToken') + ->with(null); + $cartsApiMock->expects($this->once()) + ->method('getOrderCollection') + ->willReturn($orderCollectionMock); + $helperMock->expects($this->once()) + ->method('addResendFilter') + ->with($newCartsCollectionMock, self::MAGENTO_STORE_ID, Ebizmarts_MailChimp_Model_Config::IS_QUOTE); + $newCartsCollectionMock->expects($this->exactly(5)) + ->method('addFieldToFilter') + ->withConsecutive( + array(self::STRING_IS_ACTIVE, $arrayAddFieldToFilter), + array($stringCustomerEmail, $arrayAddFieldToFilterCustomerEmail), + array($stringItemsCount, $arrayAddFieldToFilterItemsCount), + array(self::STRING_STORE_ID, $arrayAddFieldToFilterStoreId), + array($stringUpdatedAt, $arrayAddFieldToFilterUpdatedAt) + ); + $newCartsCollectionMock->expects($this->exactly(2)) + ->method('getSelect') + ->willReturnOnConsecutiveCalls( + $varienSelectMock, + $varienSelectMock + ); + $newCartsCollectionMock->expects($this->once()) + ->method('getIterator') + ->willReturn(new ArrayIterator(array($cartModelMock))); + $varienSelectMock->expects($this->once()) + ->method('where') + ->with($where); + $varienSelectMock->expects($this->once()) + ->method('limit') + ->with(self::BATCH_LIMIT_FROM_CONFIG); + $customerModelMock->expects($this->once()) + ->method('setWebsiteId') + ->with(self::WEB_SITE_ID_FROM_MAGENTO_STORE_ID); + $customerModelMock->expects($this->once()) + ->method('loadByEmail') + ->with(self::CUSTOMER_EMAIL_BY_CART); + $customerModelMock->expects($this->once()) + ->method('getEmail') + ->willReturn($customerEmailAddress); + $quoteByEmailResoureceCollectionMock->expects($this->once()) + ->method('clear'); + $quoteByEmailResoureceCollectionMock->expects($this->once()) + ->method('getIterator') + ->willReturn(new ArrayIterator(array($cartByEmailModelMock))); + $cartModelMock->expects($this->exactly(4)) + ->method('getCustomerEmail') + ->willReturnOnConsecutiveCalls( + self::CUSTOMER_EMAIL_BY_CART, + self::CUSTOMER_EMAIL_BY_CART, + self::CUSTOMER_EMAIL_BY_CART, + self::CUSTOMER_EMAIL_BY_CART + ); + $cartModelMock->expects($this->once()) + ->method('getEntityId') + ->willReturn(self::CART_ID); + $cartModelMock->expects($this->once()) + ->method('getCustomerId') + ->willReturn($customerId); + $cartModelMock->expects($this->once()) + ->method('getAllVisibleItems') + ->willReturn($allVisbleItems); + $cartByEmailModelMock->expects($this->once()) + ->method('getEntityId') + ->willReturn(self::ALREADY_SENT_CART_ID); + $orderCollectionMock->expects($this->once()) + ->method('getSize') + ->willReturn($sizeOrderCollection); + $orderCollectionMock->expects($this->exactly(2)) + ->method('addFieldToFilter') + ->withConsecutive( + array($stringCustomerEmailMainTable, $addFieldToFilterOrderCollection), + array($stringUpdated, $addFieldToFilterUpdated) + ); + + $cartsApiMock->_getNewQuotes(self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID); + } + + public function testGetNewQuotesIsOrder() + { + $existFirstDate = '2018-11-30'; + $stringCustomerEmail = 'customer_email'; + $stringItemsCount = 'items_count'; + $stringUpdatedAt = 'updated_at'; + $arrayAddFieldToFilterUpdatedAt = array('gt' => $existFirstDate); + $arrayAddFieldToFilterItemsCount = array('gt' => 0); + $arrayAddFieldToFilterCustomerEmail = array('notnull' => true); + $arrayAddFieldToFilter = array('eq' => 1); + $arrayAddFieldToFilterStoreId = array('eq' => self::MAGENTO_STORE_ID); + $where = "m4m.mailchimp_sync_delta IS NULL"; + $allVisbleItems = array('item'); + $sizeOrderCollection = 1; + $addFieldToFilterOrderCollection = array('eq' => ''); + $stringCustomerEmailMainTable = 'main_table.customer_email'; + $stringUpdated = 'main_table.updated_at'; + $addFieldToFilterUpdated = array('from' => ''); + + $cartsApiMock = $this->cartsApiMock->setMethods( + array( + 'getHelper', + 'getQuoteCollection', + 'getFirstDate', + 'joinMailchimpSyncDataWithoutWhere', + 'getBatchLimitFromConfig', + '_updateSyncData', + 'getOrderCollection' + )) + ->getMock(); + $helperMock = $this + ->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->setMethods(array('addResendFilter')) + ->getMock(); + $newCartsCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Quote_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('addFieldToFilter', 'getSelect', 'getIterator')) + ->getMock(); + $varienSelectMock = $this + ->getMockBuilder(Varien_Db_Select::class) + ->disableOriginalConstructor() + ->setMethods(array('where', 'limit')) + ->getMock(); + $cartModelMock = $this + ->getMockBuilder(Mage_Sales_Model_Quote::class) + ->disableOriginalConstructor() + ->setMethods(array('getEntityId', 'getAllVisibleItems')) + ->getMock(); + $orderCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Order_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('getSize', 'addFieldToFilter')) + ->getMock(); + + $cartsApiMock->expects($this->once()) + ->method('getHelper') + ->willReturn($helperMock); + $cartsApiMock->expects($this->once()) + ->method('getQuoteCollection') + ->willReturn($newCartsCollectionMock); + $cartsApiMock->expects($this->exactly(2)) + ->method('getFirstDate') + ->willReturnOnConsecutiveCalls( + $existFirstDate, + $existFirstDate + ); + $cartsApiMock->expects($this->once()) + ->method('joinMailchimpSyncDataWithoutWhere') + ->with($newCartsCollectionMock, self::MAILCHIMP_STORE_ID); + $cartsApiMock->expects($this->once()) + ->method('getBatchLimitFromConfig') + ->willReturn(self::BATCH_LIMIT_FROM_CONFIG); + $cartsApiMock->expects($this->once()) + ->method('_updateSyncData') + ->with(self::CART_ID, self::MAILCHIMP_STORE_ID); + $cartsApiMock->expects($this->once()) + ->method('getOrderCollection') + ->willReturn($orderCollectionMock); + $helperMock->expects($this->once()) + ->method('addResendFilter') + ->with($newCartsCollectionMock, self::MAGENTO_STORE_ID, Ebizmarts_MailChimp_Model_Config::IS_QUOTE); + $newCartsCollectionMock->expects($this->exactly(5)) + ->method('addFieldToFilter') + ->withConsecutive( + array(self::STRING_IS_ACTIVE, $arrayAddFieldToFilter), + array($stringCustomerEmail, $arrayAddFieldToFilterCustomerEmail), + array($stringItemsCount, $arrayAddFieldToFilterItemsCount), + array(self::STRING_STORE_ID, $arrayAddFieldToFilterStoreId), + array($stringUpdatedAt, $arrayAddFieldToFilterUpdatedAt) + ); + $newCartsCollectionMock->expects($this->exactly(2)) + ->method('getSelect') + ->willReturnOnConsecutiveCalls( + $varienSelectMock, + $varienSelectMock + ); + $newCartsCollectionMock->expects($this->once()) + ->method('getIterator') + ->willReturn(new ArrayIterator(array($cartModelMock))); + $varienSelectMock->expects($this->once()) + ->method('where') + ->with($where); + $varienSelectMock->expects($this->once()) + ->method('limit') + ->with(self::BATCH_LIMIT_FROM_CONFIG); + $cartModelMock->expects($this->once()) + ->method('getEntityId') + ->willReturn(self::CART_ID); + $cartModelMock->expects($this->once()) + ->method('getAllVisibleItems') + ->willReturn($allVisbleItems); + $orderCollectionMock->expects($this->once()) + ->method('getSize') + ->willReturn($sizeOrderCollection); + $orderCollectionMock->expects($this->exactly(2)) + ->method('addFieldToFilter') + ->withConsecutive( + array($stringCustomerEmailMainTable, $addFieldToFilterOrderCollection), + array($stringUpdated, $addFieldToFilterUpdated) + ); + + $cartsApiMock->_getNewQuotes(self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID); + } + + public function testGetNewQuotesEmpty() + { + $existFirstDate = '2018-11-30'; + $stringCustomerEmail = 'customer_email'; + $stringItemsCount = 'items_count'; + $stringUpdatedAt = 'updated_at'; + $arrayAddFieldToFilterUpdatedAt = array('gt' => $existFirstDate); + $arrayAddFieldToFilterItemsCount = array('gt' => 0); + $arrayAddFieldToFilterCustomerEmail = array('notnull' => true); + $arrayAddFieldToFilter = array('eq' => 1); + $arrayAddFieldToFilterStoreId = array('eq' => self::MAGENTO_STORE_ID); + $where = "m4m.mailchimp_sync_delta IS NULL"; + $allVisbleItems = array(); + $addFieldToFilterOrderCollection = array('eq' => ''); + $stringCustomerEmailMainTable = 'main_table.customer_email'; + $stringUpdated = 'main_table.updated_at'; + $addFieldToFilterUpdated = array('from' => ''); + + $cartsApiMock = $this->cartsApiMock->setMethods( + array( + 'getHelper', + 'getQuoteCollection', + 'getFirstDate', + 'joinMailchimpSyncDataWithoutWhere', + 'getBatchLimitFromConfig', + '_updateSyncData', + 'getOrderCollection' + )) + ->getMock(); + $helperMock = $this + ->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->setMethods(array('addResendFilter')) + ->getMock(); + $newCartsCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Quote_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('addFieldToFilter', 'getSelect', 'getIterator')) + ->getMock(); + $varienSelectMock = $this + ->getMockBuilder(Varien_Db_Select::class) + ->disableOriginalConstructor() + ->setMethods(array('where', 'limit')) + ->getMock(); + $cartModelMock = $this + ->getMockBuilder(Mage_Sales_Model_Quote::class) + ->disableOriginalConstructor() + ->setMethods(array('getEntityId', 'getAllVisibleItems')) + ->getMock(); + $orderCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Order_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('addFieldToFilter')) + ->getMock(); + + $cartsApiMock->expects($this->once()) + ->method('getHelper') + ->willReturn($helperMock); + $cartsApiMock->expects($this->once()) + ->method('getQuoteCollection') + ->willReturn($newCartsCollectionMock); + $cartsApiMock->expects($this->exactly(2)) + ->method('getFirstDate') + ->willReturnOnConsecutiveCalls( + $existFirstDate, + $existFirstDate + ); + $cartsApiMock->expects($this->once()) + ->method('joinMailchimpSyncDataWithoutWhere') + ->with($newCartsCollectionMock, self::MAILCHIMP_STORE_ID); + $cartsApiMock->expects($this->once()) + ->method('getBatchLimitFromConfig') + ->willReturn(self::BATCH_LIMIT_FROM_CONFIG); + $cartsApiMock->expects($this->once()) + ->method('_updateSyncData') + ->with(self::CART_ID, self::MAILCHIMP_STORE_ID); + $cartsApiMock->expects($this->once()) + ->method('getOrderCollection') + ->willReturn($orderCollectionMock); + $helperMock->expects($this->once()) + ->method('addResendFilter') + ->with($newCartsCollectionMock, self::MAGENTO_STORE_ID, Ebizmarts_MailChimp_Model_Config::IS_QUOTE); + $newCartsCollectionMock->expects($this->exactly(5)) + ->method('addFieldToFilter') + ->withConsecutive( + array(self::STRING_IS_ACTIVE, $arrayAddFieldToFilter), + array($stringCustomerEmail, $arrayAddFieldToFilterCustomerEmail), + array($stringItemsCount, $arrayAddFieldToFilterItemsCount), + array(self::STRING_STORE_ID, $arrayAddFieldToFilterStoreId), + array($stringUpdatedAt, $arrayAddFieldToFilterUpdatedAt) + ); + $newCartsCollectionMock->expects($this->exactly(2)) + ->method('getSelect') + ->willReturnOnConsecutiveCalls( + $varienSelectMock, + $varienSelectMock + ); + $newCartsCollectionMock->expects($this->once()) + ->method('getIterator') + ->willReturn(new ArrayIterator(array($cartModelMock))); + $varienSelectMock->expects($this->once()) + ->method('where') + ->with($where); + $varienSelectMock->expects($this->once()) + ->method('limit') + ->with(self::BATCH_LIMIT_FROM_CONFIG); + $cartModelMock->expects($this->once()) + ->method('getEntityId') + ->willReturn(self::CART_ID); + $cartModelMock->expects($this->once()) + ->method('getAllVisibleItems') + ->willReturn($allVisbleItems); + $orderCollectionMock->expects($this->exactly(2)) + ->method('addFieldToFilter') + ->withConsecutive( + array($stringCustomerEmailMainTable, $addFieldToFilterOrderCollection), + array($stringUpdated, $addFieldToFilterUpdated) + ); + + $cartsApiMock->_getNewQuotes(self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID); + } + + public function testGetNewQuotesGuestCustomer() + { + $existFirstDate = '2018-11-30'; + $customerId = ''; + $customerEmailAddress = 'test@ebizmarts.com'; + $stringCustomerEmail = 'customer_email'; + $stringItemsCount = 'items_count'; + $stringUpdatedAt = 'updated_at'; + $arrayAddFieldToFilterUpdatedAt = array('gt' => $existFirstDate); + $arrayAddFieldToFilterItemsCount = array('gt' => 0); + $arrayAddFieldToFilterCustomerEmail = array('notnull' => true); + $arrayAddFieldToFilter = array('eq' => 1); + $arrayAddFieldToFilterStoreId = array('eq' => self::MAGENTO_STORE_ID); + $where = "m4m.mailchimp_sync_delta IS NULL"; + $allVisbleItems = array('item'); + $sizeOrderCollection = 0; + $addFieldToFilterOrderCollection = array('eq' => self::CUSTOMER_EMAIL_BY_CART); + $stringCustomerEmailMainTable = 'main_table.customer_email'; + $stringUpdated = 'main_table.updated_at'; + $addFieldToFilterUpdated = array('from' => ''); + + $cartsApiMock = $this->cartsApiMock->setMethods( + array( + 'getHelper', + 'getQuoteCollection', + 'getFirstDate', + 'joinMailchimpSyncDataWithoutWhere', + 'getBatchLimitFromConfig', + '_updateSyncData', + 'getCustomerModel', + 'getWebSiteIdFromMagentoStoreId', + 'getBatchId', + 'getOrderCollection' + )) + ->getMock(); + $helperMock = $this + ->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->setMethods(array('addResendFilter')) + ->getMock(); + $newCartsCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Quote_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('addFieldToFilter', 'getSelect', 'getIterator')) + ->getMock(); + $varienSelectMock = $this + ->getMockBuilder(Varien_Db_Select::class) + ->disableOriginalConstructor() + ->setMethods(array('where', 'limit')) + ->getMock(); + $customerModelMock = $this + ->getMockBuilder(Mage_Customer_Model_Customer::class) + ->disableOriginalConstructor() + ->setMethods(array('setWebsiteId', 'loadByEmail', 'getEmail')) + ->getMock(); + $cartModelMock = $this + ->getMockBuilder(Mage_Sales_Model_Quote::class) + ->disableOriginalConstructor() + ->setMethods(array('getEntityId', 'getCustomerEmail', 'getCustomerId', 'getAllVisibleItems')) + ->getMock(); + $orderCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Order_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('getSize', 'addFieldToFilter')) + ->getMock(); + + $cartsApiMock->expects($this->once()) + ->method('getHelper') + ->willReturn($helperMock); + $cartsApiMock->expects($this->once()) + ->method('getQuoteCollection') + ->willReturn($newCartsCollectionMock); + $cartsApiMock->expects($this->exactly(2)) + ->method('getFirstDate') + ->willReturnOnConsecutiveCalls( + $existFirstDate, + $existFirstDate + ); + $cartsApiMock->expects($this->once()) + ->method('joinMailchimpSyncDataWithoutWhere') + ->with($newCartsCollectionMock, self::MAILCHIMP_STORE_ID); + $cartsApiMock->expects($this->once()) + ->method('getBatchLimitFromConfig') + ->willReturn(self::BATCH_LIMIT_FROM_CONFIG); + $cartsApiMock->expects($this->once()) + ->method('_updateSyncData') + ->with(self::CART_ID, self::MAILCHIMP_STORE_ID); + $cartsApiMock->expects($this->once()) + ->method('getCustomerModel') + ->willReturn($customerModelMock); + $cartsApiMock->expects($this->once()) + ->method('getWebSiteIdFromMagentoStoreId') + ->with(self::MAGENTO_STORE_ID) + ->willReturn(self::WEB_SITE_ID_FROM_MAGENTO_STORE_ID); + $cartsApiMock->expects($this->once()) + ->method('getBatchId') + ->willReturn(self::BATCH_ID); + $cartsApiMock->expects($this->once()) + ->method('getOrderCollection') + ->willReturn($orderCollectionMock); + $helperMock->expects($this->once()) + ->method('addResendFilter') + ->with($newCartsCollectionMock, self::MAGENTO_STORE_ID, Ebizmarts_MailChimp_Model_Config::IS_QUOTE); + $newCartsCollectionMock->expects($this->exactly(5)) + ->method('addFieldToFilter') + ->withConsecutive( + array(self::STRING_IS_ACTIVE, $arrayAddFieldToFilter), + array($stringCustomerEmail, $arrayAddFieldToFilterCustomerEmail), + array($stringItemsCount, $arrayAddFieldToFilterItemsCount), + array(self::STRING_STORE_ID, $arrayAddFieldToFilterStoreId), + array($stringUpdatedAt, $arrayAddFieldToFilterUpdatedAt) + ); + $newCartsCollectionMock->expects($this->exactly(2)) + ->method('getSelect') + ->willReturnOnConsecutiveCalls( + $varienSelectMock, + $varienSelectMock + ); + $newCartsCollectionMock->expects($this->once()) + ->method('getIterator') + ->willReturn(new ArrayIterator(array($cartModelMock))); + $varienSelectMock->expects($this->once()) + ->method('where') + ->with($where); + $varienSelectMock->expects($this->once()) + ->method('limit') + ->with(self::BATCH_LIMIT_FROM_CONFIG); + $customerModelMock->expects($this->once()) + ->method('setWebsiteId') + ->with(self::WEB_SITE_ID_FROM_MAGENTO_STORE_ID); + $customerModelMock->expects($this->once()) + ->method('loadByEmail') + ->with(self::CUSTOMER_EMAIL_BY_CART); + $customerModelMock->expects($this->exactly(2)) + ->method('getEmail') + ->willReturnOnConsecutiveCalls( + $customerEmailAddress, + $customerEmailAddress + ); + $cartModelMock->expects($this->exactly(4)) + ->method('getCustomerEmail') + ->willReturnOnConsecutiveCalls( + self::CUSTOMER_EMAIL_BY_CART, + self::CUSTOMER_EMAIL_BY_CART, + self::CUSTOMER_EMAIL_BY_CART, + self::CUSTOMER_EMAIL_BY_CART + ); + $cartModelMock->expects($this->once()) + ->method('getEntityId') + ->willReturn(self::CART_ID); + $cartModelMock->expects($this->once()) + ->method('getCustomerId') + ->willReturn($customerId); + $cartModelMock->expects($this->once()) + ->method('getAllVisibleItems') + ->willReturn($allVisbleItems); + $orderCollectionMock->expects($this->once()) + ->method('getSize') + ->willReturn($sizeOrderCollection); + $orderCollectionMock->expects($this->exactly(2)) + ->method('addFieldToFilter') + ->withConsecutive( + array($stringCustomerEmailMainTable, $addFieldToFilterOrderCollection), + array($stringUpdated, $addFieldToFilterUpdated) + ); + + $cartsApiMock->_getNewQuotes(self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID); + } + + public function testGetNewQuotesEmptyJson() + { + $existFirstDate = '2018-11-30'; + $customerId = 1; + $customerEmailAddress = ''; + $allCarts = array(array('method' => 'DELETE', 'path' => '/ecommerce/stores/'.self::MAILCHIMP_STORE_ID.'/carts/'. self::ALREADY_SENT_CART_ID, 'operation_id' => self::BATCH_ID . '_' . self::ALREADY_SENT_CART_ID, 'body' => '')); + $cartJson = ''; + $stringCustomerEmail = 'customer_email'; + $stringItemsCount = 'items_count'; + $stringUpdatedAt = 'updated_at'; + $arrayAddFieldToFilterUpdatedAt = array('gt' => $existFirstDate); + $arrayAddFieldToFilterItemsCount = array('gt' => 0); + $arrayAddFieldToFilterCustomerEmail = array('notnull' => true); + $arrayAddFieldToFilter = array('eq' => 1); + $arrayAddFieldToFilterStoreId = array('eq' => self::MAGENTO_STORE_ID); + $where = "m4m.mailchimp_sync_delta IS NULL"; + $allVisbleItems = array('item'); + $sizeOrderCollection = 0; + $addFieldToFilterOrderCollection = array('eq' => self::CUSTOMER_EMAIL_BY_CART); + $stringCustomerEmailMainTable = 'main_table.customer_email'; + $stringUpdated = 'main_table.updated_at'; + $addFieldToFilterUpdated = array('from' => ''); + + $cartsApiMock = $this->cartsApiMock->setMethods( + array( + 'getHelper', + 'getQuoteCollection', + 'getFirstDate', + 'joinMailchimpSyncDataWithoutWhere', + 'getBatchLimitFromConfig', + '_updateSyncData', + 'getCustomerModel', + 'getWebSiteIdFromMagentoStoreId', + 'getAllCartsByEmail', + 'getCounter', + 'getBatchId', + 'setCounter', + 'addProductNotSentData', + '_makeCart', + 'setToken', + 'getOrderCollection' + )) + ->getMock(); + $helperMock = $this + ->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->setMethods(array('addResendFilter')) + ->getMock(); + $newCartsCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Quote_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('addFieldToFilter', 'getSelect', 'getIterator')) + ->getMock(); + $varienSelectMock = $this + ->getMockBuilder(Varien_Db_Select::class) + ->disableOriginalConstructor() + ->setMethods(array('where', 'limit')) + ->getMock(); + $customerModelMock = $this + ->getMockBuilder(Mage_Customer_Model_Customer::class) + ->disableOriginalConstructor() + ->setMethods(array('setWebsiteId', 'loadByEmail', 'getEmail')) + ->getMock(); + $quoteByEmailResoureceCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Quote_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('clear', 'getIterator')) + ->getMock(); + $cartModelMock = $this + ->getMockBuilder(Mage_Sales_Model_Quote::class) + ->disableOriginalConstructor() + ->setMethods(array('getEntityId', 'getCustomerEmail', 'getCustomerId', 'getAllVisibleItems')) + ->getMock(); + $cartByEmailModelMock = $this + ->getMockBuilder(Mage_Sales_Model_Quote::class) + ->disableOriginalConstructor() + ->setMethods(array('getEntityId')) + ->getMock(); + $orderCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Order_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('getSize', 'addFieldToFilter')) + ->getMock(); + + $cartsApiMock->expects($this->once()) + ->method('getHelper') + ->willReturn($helperMock); + $cartsApiMock->expects($this->once()) + ->method('getQuoteCollection') + ->willReturn($newCartsCollectionMock); + $cartsApiMock->expects($this->exactly(2)) + ->method('getFirstDate') + ->willReturnOnConsecutiveCalls( + $existFirstDate, + $existFirstDate + ); + $cartsApiMock->expects($this->once()) + ->method('joinMailchimpSyncDataWithoutWhere') + ->with($newCartsCollectionMock, self::MAILCHIMP_STORE_ID); + $cartsApiMock->expects($this->once()) + ->method('getBatchLimitFromConfig') + ->willReturn(self::BATCH_LIMIT_FROM_CONFIG); + $cartsApiMock->expects($this->exactly(2)) + ->method('_updateSyncData') + ->withConsecutive( + array(self::ALREADY_SENT_CART_ID, self::MAILCHIMP_STORE_ID, null, null, null, null, 1), + array(self::CART_ID, self::MAILCHIMP_STORE_ID) + ); + $cartsApiMock->expects($this->once()) + ->method('getCustomerModel') + ->willReturn($customerModelMock); + $cartsApiMock->expects($this->once()) + ->method('getWebSiteIdFromMagentoStoreId') + ->with(self::MAGENTO_STORE_ID) + ->willReturn(self::WEB_SITE_ID_FROM_MAGENTO_STORE_ID); + $cartsApiMock->expects($this->once()) + ->method('getAllCartsByEmail') + ->with(self::CUSTOMER_EMAIL_BY_CART,self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID) + ->willReturn($quoteByEmailResoureceCollectionMock); + $cartsApiMock->expects($this->exactly(2)) + ->method('getCounter') + ->willReturnOnConsecutiveCalls( + self::COUNTER, + self::COUNTER + ); + $cartsApiMock->expects($this->once()) + ->method('getBatchId') + ->willReturn(self::BATCH_ID); + $cartsApiMock->expects($this->once()) + ->method('setCounter') + ->with(self::COUNTER + 1); + $cartsApiMock->expects($this->once()) + ->method('addProductNotSentData') + ->with(self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID, $cartModelMock, $allCarts) + ->willReturn($allCarts); + $cartsApiMock->expects($this->once()) + ->method('_makeCart') + ->with($cartModelMock, self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID) + ->willReturn($cartJson); + $cartsApiMock->expects($this->once()) + ->method('setToken') + ->with(null); + $cartsApiMock->expects($this->once()) + ->method('getOrderCollection') + ->willReturn($orderCollectionMock); + $helperMock->expects($this->once()) + ->method('addResendFilter') + ->with($newCartsCollectionMock, self::MAGENTO_STORE_ID, Ebizmarts_MailChimp_Model_Config::IS_QUOTE); + $newCartsCollectionMock->expects($this->exactly(5)) + ->method('addFieldToFilter') + ->withConsecutive( + array(self::STRING_IS_ACTIVE, $arrayAddFieldToFilter), + array($stringCustomerEmail, $arrayAddFieldToFilterCustomerEmail), + array($stringItemsCount, $arrayAddFieldToFilterItemsCount), + array(self::STRING_STORE_ID, $arrayAddFieldToFilterStoreId), + array($stringUpdatedAt, $arrayAddFieldToFilterUpdatedAt) + ); + $newCartsCollectionMock->expects($this->exactly(2)) + ->method('getSelect') + ->willReturnOnConsecutiveCalls( + $varienSelectMock, + $varienSelectMock + ); + $newCartsCollectionMock->expects($this->once()) + ->method('getIterator') + ->willReturn(new ArrayIterator(array($cartModelMock))); + $varienSelectMock->expects($this->once()) + ->method('where') + ->with($where); + $varienSelectMock->expects($this->once()) + ->method('limit') + ->with(self::BATCH_LIMIT_FROM_CONFIG); + $customerModelMock->expects($this->once()) + ->method('setWebsiteId') + ->with(self::WEB_SITE_ID_FROM_MAGENTO_STORE_ID); + $customerModelMock->expects($this->once()) + ->method('loadByEmail') + ->with(self::CUSTOMER_EMAIL_BY_CART); + $customerModelMock->expects($this->once()) + ->method('getEmail') + ->willReturn($customerEmailAddress); + $quoteByEmailResoureceCollectionMock->expects($this->once()) + ->method('clear'); + $quoteByEmailResoureceCollectionMock->expects($this->once()) + ->method('getIterator') + ->willReturn(new ArrayIterator(array($cartByEmailModelMock))); + $cartModelMock->expects($this->exactly(4)) + ->method('getCustomerEmail') + ->willReturnOnConsecutiveCalls( + self::CUSTOMER_EMAIL_BY_CART, + self::CUSTOMER_EMAIL_BY_CART, + self::CUSTOMER_EMAIL_BY_CART, + self::CUSTOMER_EMAIL_BY_CART + ); + $cartModelMock->expects($this->once()) + ->method('getEntityId') + ->willReturn(self::CART_ID); + $cartModelMock->expects($this->once()) + ->method('getCustomerId') + ->willReturn($customerId); + $cartModelMock->expects($this->once()) + ->method('getAllVisibleItems') + ->willReturn($allVisbleItems); + $cartByEmailModelMock->expects($this->once()) + ->method('getEntityId') + ->willReturn(self::ALREADY_SENT_CART_ID); + $orderCollectionMock->expects($this->once()) + ->method('getSize') + ->willReturn($sizeOrderCollection); + $orderCollectionMock->expects($this->exactly(2)) + ->method('addFieldToFilter') + ->withConsecutive( + array($stringCustomerEmailMainTable, $addFieldToFilterOrderCollection), + array($stringUpdated, $addFieldToFilterUpdated) + ); + + $cartsApiMock->_getNewQuotes(self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID); + } + + public function testGetAllCartsByEmail() + { + $mailchimpTableName = 'm4m'; + $stringIsActive = 'is_active'; + $arrayAddToFilterIsActive = array('eq' => 1); + $stringStoreId = 'store_id'; + $arrayAddToFilterStoreId = array('eq' => self::MAGENTO_STORE_ID); + $stringCustomerId = 'customer_email'; + $arrayAddToFilterCustomerId = array('eq' => self::CUSTOMER_EMAIL_BY_CART); + $arrayMailchimpTableName = array('m4m' => $mailchimpTableName); + $condition = "m4m.related_id = main_table.entity_id and m4m.type = '" . Ebizmarts_MailChimp_Model_Config::IS_QUOTE . "' + AND m4m.mailchimp_store_id = '" . self::MAILCHIMP_STORE_ID . "'"; + $m4m = array('m4m.*'); + $where = "m4m.mailchimp_sync_deleted = 0 AND m4m.mailchimp_store_id = '" . self::MAILCHIMP_STORE_ID . "'"; + + $cartsApiMock = $this->cartsApiMock + ->setMethods(array('getMailchimpEcommerceDataTableName', 'getQuoteCollection')) + ->getMock(); + $newCartsCollectionMock = $this + ->getMockBuilder(Mage_Sales_Model_Resource_Quote_Collection::class) + ->disableOriginalConstructor() + ->setMethods(array('addFieldToFilter', 'getSelect')) + ->getMock(); + $varienSelectMock = $this + ->getMockBuilder(Varien_Db_Select::class) + ->disableOriginalConstructor() + ->setMethods(array('where', 'joinLeft')) + ->getMock(); + + $cartsApiMock->expects($this->once()) + ->method('getMailchimpEcommerceDataTableName') + ->willReturn($mailchimpTableName); + $cartsApiMock->expects($this->once()) + ->method('getQuoteCollection') + ->willReturn($newCartsCollectionMock); + + $newCartsCollectionMock->expects($this->exactly(3)) + ->method('addFieldToFilter') + ->withConsecutive( + array($stringIsActive, $arrayAddToFilterIsActive), + array($stringStoreId, $arrayAddToFilterStoreId), + array($stringCustomerId, $arrayAddToFilterCustomerId) + ); + $newCartsCollectionMock->expects($this->exactly(2)) + ->method('getSelect') + ->willReturnOnConsecutiveCalls( + $varienSelectMock, + $varienSelectMock + ); - $helperMock->expects($this->once())->method('isAbandonedCartEnabled')->with($magentoStoreId)->willReturn(true); - $helperMock->expects($this->once())->method('getAbandonedCartFirstDate')->with($magentoStoreId)->willReturn('00-00-00 00:00:00'); - $helperMock->expects($this->once())->method('getDateMicrotime')->willReturn('00-00-00 00:00:00'); - $helperMock->expects($this->once())->method('getResendTurn')->with($magentoStoreId)->willReturn(null); + $varienSelectMock->expects($this->once()) + ->method('joinLeft') + ->with($arrayMailchimpTableName, $condition, $m4m); + $varienSelectMock->expects($this->once()) + ->method('where') + ->with($where); - $cartsApiMock->createBatchJson($mailchimpStoreId, $magentoStoreId); + $cartsApiMock->getAllCartsByEmail(self::CUSTOMER_EMAIL_BY_CART, self::MAILCHIMP_STORE_ID, self::MAGENTO_STORE_ID); } } diff --git a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/CustomersTest.php b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/CustomersTest.php index 7c217474a..8db205bf2 100644 --- a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/CustomersTest.php +++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/CustomersTest.php @@ -54,6 +54,8 @@ public function testGetOptInNoDefaultStore() public function testCreateBatchJson() { $mailchimpStoreId = 'a1s2d3f4g5h6j7k8l9n0'; + $customerEmail = 'keller@ebizmarts.com'; + $subscriberId = 1; $storeId = 1; $optInStatus = true; $customerId = 142; @@ -77,7 +79,7 @@ public function testCreateBatchJson() $this->customersApiMock = $this->customersApiMock->setMethods( array('makeBatchId', 'joinMailchimpSyncData', 'makeCustomersNotSentCollection', 'getOptin', 'getBatchMagentoStoreId', '_buildCustomerData', 'makePutBatchStructure', - '_updateSyncData', 'setMailchimpStoreId', 'setMagentoStoreId', 'getCustomerResourceCollection' + '_updateSyncData', 'setMailchimpStoreId', 'setMagentoStoreId', 'getCustomerResourceCollection', 'getSubscriberModel' ) ) ->getMock(); @@ -88,11 +90,27 @@ public function testCreateBatchJson() $customerMock = $this->getMockBuilder(Mage_Customer_Model_Customer::class) ->disableOriginalConstructor() - ->setMethods(array('getId')) + ->setMethods(array('getId', 'getEmail')) ->getMock(); + $subscriberMock = $this->getMockBuilder(Mage_Newsletter_Model_Subscriber::class) + ->disableOriginalConstructor() + ->setMethods(array('loadByEmail')) + ->getMock(); + + $subscribersMailchimpMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Subscriber::class) + ->disableOriginalConstructor() + ->setMethods(array('getSubscriberId')) + ->getMock(); + $customerArray = array($customerMock); + $this->customersApiMock->expects($this->once())->method('getSubscriberModel')->willReturn($subscriberMock); + + $subscriberMock->expects($this->once())->method('loadByEmail')->with($customerEmail)->willReturn($subscribersMailchimpMock); + + $subscribersMailchimpMock->expects($this->once())->method('getSubscriberId')->willReturn($subscriberId); + $this->customersApiMock->expects($this->once())->method('setMailchimpStoreId')->with($mailchimpStoreId); $this->customersApiMock->expects($this->once())->method('setMagentoStoreId')->with($storeId); @@ -112,6 +130,7 @@ public function testCreateBatchJson() $this->customersApiMock->expects($this->once())->method('makePutBatchStructure')->with($customerJson)->willReturn($operationData); $customerMock->expects($this->once())->method('getId')->willReturn($customerId); + $customerMock->expects($this->any())->method('getEmail')->willReturn($customerEmail); $this->customersApiMock->expects($this->once())->method('_updateSyncData')->with($customerId, $mailchimpStoreId); diff --git a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/ProductsTest.php b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/ProductsTest.php index 91d1bf4a3..c210f3e41 100644 --- a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/ProductsTest.php +++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/ProductsTest.php @@ -620,4 +620,45 @@ public function invokeMethod(&$object, $methodName, array $parameters = array()) return $method->invokeArgs($object, $parameters); } + public function testUpdate() + { + $parentIdArray = array(282, 283, 284, 510, 511, 878, 880, 881); + $productId = 877; + $mailchimpStoreId = '3ade9d9e52e35e9b18d95bdd4d9e9a44'; + + $productsApiMock = $this->productsApiMock + ->setMethods(array('getAllParentIds', '_updateSyncData')) + ->getMock(); + + $productIdArrayMock = $this->getMockBuilder(ArrayObject::class) + ->setMethods(array('getIterator')) + ->getMock(); + + $productsApiMock->expects($this->once()) + ->method('getAllParentIds') + ->with($productId) + ->willReturn($productIdArrayMock); + + + $productIdArrayMock->expects($this->once()) + ->method('getIterator') + ->willReturn(new ArrayIterator($parentIdArray)); + + $productsApiMock->expects($this->exactly(9)) + ->method('_updateSyncData') + ->withConsecutive( + array($parentIdArray[0], $mailchimpStoreId, null, null, 1, null, null, true, false), + array($parentIdArray[1], $mailchimpStoreId, null, null, 1, null, null, true, false), + array($parentIdArray[2], $mailchimpStoreId, null, null, 1, null, null, true, false), + array($parentIdArray[3], $mailchimpStoreId, null, null, 1, null, null, true, false), + array($parentIdArray[4], $mailchimpStoreId, null, null, 1, null, null, true, false), + array($parentIdArray[5], $mailchimpStoreId, null, null, 1, null, null, true, false), + array($parentIdArray[6], $mailchimpStoreId, null, null, 1, null, null, true, false), + array($parentIdArray[7], $mailchimpStoreId, null, null, 1, null, null, true, false), + array($productId, $mailchimpStoreId, null, null, 1, null, null, true, false) + ); + + $productsApiMock->update($productId, $mailchimpStoreId); + } + } diff --git a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/StoresTest.php b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/StoresTest.php index 0ca57937b..23c1f181c 100644 --- a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/StoresTest.php +++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/Api/StoresTest.php @@ -205,7 +205,7 @@ public function testModifyName() $apiStoresMock->modifyName($name, $scopeId, $scope); } - public function testGetMCJsUrl() + public function testRetrieveAndSaveMCJsUrlInConfig() { $mailChimpStoreId = 'a1s2d3f4g5h6j7k8l9n0'; $scopeId = 1; @@ -239,8 +239,8 @@ public function testGetMCJsUrl() $helperMock->expects($this->once())->method('getRealScopeForConfig')->with(Ebizmarts_MailChimp_Model_Config::GENERAL_LIST, $scopeId, $scope)->willReturn($realScope); $helperMock->expects($this->once())->method('saveMailchimpConfig')->with($configValues, $realScope['scope_id'], $realScope['scope']); - $return = $apiStoresMock->getMCJsUrl($scopeId, $scope); + $return = $apiStoresMock->retrieveAndSaveMCJsUrlInConfig($scopeId, $scope); - $this->assertEquals($MCJsUrl, $return); + $this->assertEquals(true, $return); } } diff --git a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/ObserverTest.php b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/ObserverTest.php old mode 100644 new mode 100755 index 877adf3d3..b5123cddb --- a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/ObserverTest.php +++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/Model/ObserverTest.php @@ -202,6 +202,7 @@ public function testChangeStoreName() $stores[] = $storeMock; $eventObserverMock->expects($this->once())->method('getStore')->willReturn($storeMock); + $storeMock->expects($this->once())->method('getId')->willReturn($storeId); $observerMock->expects($this->once())->method('changeStoreNameIfModuleEnabled')->with($storeId); @@ -291,17 +292,20 @@ public function testHandleSubscriberDeletion() $observerMock->handleSubscriberDeletion($eventObserverMock); } - public function testCustomerSaveBefore() + public function testCustomerSaveAfter() { + $adminStoreId = 0; $storeId = 1; $oldEmailAddress = 'oldEmail@example.com'; $newEmailAddress = 'newEmail@example.com'; + $subscriberEmail = ($oldEmailAddress) ? $oldEmailAddress : $newEmailAddress; $subscriberId = 1; $customerId = 1; + $params = array(); $customerMock = $this->getMockBuilder(Mage_Customer_Model_Customer::class) ->disableOriginalConstructor() - ->setMethods(array('getId', 'getOrigData', 'getEmail', 'getStoreId')) + ->setMethods(array('getId', 'getOrigData', 'getEmail', 'getStoreId', 'getMailchimpStoreView')) ->getMock(); $eventObserverMock = $this->getMockBuilder(Varien_Event_Observer::class) @@ -314,9 +318,14 @@ public function testCustomerSaveBefore() ->setMethods(array('getCustomer')) ->getMock(); + $requestMock = $this->getMockBuilder(Mage_Core_Controller_Request_Http::class) + ->disableOriginalConstructor() + ->setMethods(array('getParams')) + ->getMock(); + $observerMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Observer::class) ->disableOriginalConstructor() - ->setMethods(array('makeHelper', 'makeApiSubscriber', 'getSubscriberModel', 'makeApiCustomer')) + ->setMethods(array('makeHelper', 'makeApiSubscriber', 'getSubscriberModel', 'makeApiCustomer', 'getRequest', 'handleCustomerGroups')) ->getMock(); $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) @@ -331,7 +340,12 @@ public function testCustomerSaveBefore() $subscriberMock = $this->getMockBuilder(Mage_Newsletter_Model_Subscriber::class) ->disableOriginalConstructor() - ->setMethods(array('loadByEmail', 'loadByCustomer', 'setSubscriberEmail', 'getId')) + ->setMethods(array('getId')) + ->getMock(); + + $subscriberMockTwo = $this->getMockBuilder(Mage_Newsletter_Model_Subscriber::class) + ->disableOriginalConstructor() + ->setMethods(array('loadByCustomer', 'setSubscriberEmail', 'save')) ->getMock(); $apiCustomerMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Api_Customers::class) @@ -343,39 +357,41 @@ public function testCustomerSaveBefore() $eventMock->expects($this->once())->method('getCustomer')->willReturn($customerMock); - $customerMock->expects($this->once())->method('getStoreId')->willReturn($storeId); + $customerMock->expects($this->once())->method('getOrigData')->with('email')->willReturn($oldEmailAddress); + $customerMock->expects($this->once())->method('getEmail')->willReturn($newEmailAddress); + $customerMock->expects($this->once())->method('getStoreId')->willReturn($adminStoreId); + $customerMock->expects($this->once())->method('getMailchimpStoreView')->willReturn($storeId); $observerMock->expects($this->once())->method('makeHelper')->willReturn($helperMock); $helperMock->expects($this->once())->method('isSubscriptionEnabled')->with($storeId)->willReturn(true); - $observerMock->expects($this->once())->method('makeApiSubscriber')->willReturn($apiSubscriberMock); + $observerMock->expects($this->once())->method('getRequest')->willReturn($requestMock); - $customerMock->expects($this->once())->method('getOrigData')->with('email')->willReturn($oldEmailAddress); - $customerMock->expects($this->once())->method('getEmail')->willReturn($newEmailAddress); + $requestMock->expects($this->once())->method('getParams')->willReturn($params); + + $customerMock->expects($this->once())->method('getId')->willReturn($customerId); - $observerMock->expects($this->once())->method('getSubscriberModel')->willReturn($subscriberMock); + $observerMock->expects($this->once())->method('handleCustomerGroups')->with($subscriberEmail, $params, $storeId, $customerId)->willReturn($subscriberMock); + $observerMock->expects($this->once())->method('makeApiSubscriber')->willReturn($apiSubscriberMock); - $subscriberMock->expects($this->once())->method('loadByEmail')->with($oldEmailAddress)->willReturnSelf(); $subscriberMock->expects($this->once())->method('getId')->willReturn($subscriberId); $apiSubscriberMock->expects($this->once())->method('deleteSubscriber')->with($subscriberMock); - $subscriberMock->expects($this->once())->method('loadByCustomer')->with($customerMock)->willReturnSelf(); - $subscriberMock->expects($this->once())->method('setSubscriberEmail')->with($newEmailAddress); + $observerMock->expects($this->once())->method('getSubscriberModel')->willReturn($subscriberMockTwo); - $apiSubscriberMock->expects($this->once())->method('updateSubscriber')->with($subscriberMock, true); - $apiSubscriberMock->expects($this->once())->method('update')->with($newEmailAddress, $storeId); + $subscriberMockTwo->expects($this->once())->method('loadByCustomer')->with($customerMock)->willReturnSelf(); + $subscriberMockTwo->expects($this->once())->method('setSubscriberEmail')->with($newEmailAddress); + $subscriberMockTwo->expects($this->once())->method('save')->willReturnSelf(); $helperMock->expects($this->once())->method('isEcomSyncDataEnabled')->with($storeId)->willReturn(true); $observerMock->expects($this->once())->method('makeApiCustomer')->willReturn($apiCustomerMock); - $customerMock->expects($this->once())->method('getId')->willReturn($customerId); - $apiCustomerMock->expects($this->once())->method('update')->with($customerId, $storeId); - $observerMock->customerSaveBefore($eventObserverMock); + $observerMock->customerSaveAfter($eventObserverMock); } public function testCustomerAddressSaveBefore() @@ -649,8 +665,14 @@ public function testAddColumnToSalesOrderGridCollection() $observerMock->addColumnToSalesOrderGridCollection($eventObserverMock); } - public function testHandleSubscriber() + + /** + * @param array $data + * @dataProvider subscriberSaveBeforeDataProvider + */ + public function testSubscriberSaveBefore($data) { + $getStoreId = $data['getStoreId']; $storeId = 1; $eventObserverMock = $this->getMockBuilder(Varien_Event_Observer::class) @@ -660,14 +682,13 @@ public function testHandleSubscriber() $observerMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Observer::class) ->disableOriginalConstructor() - ->setMethods(array('makeHelper', 'getCoreResource', 'getRegistry', 'removeRegistry', 'createEmailCookie', - 'makeApiSubscriber', 'addSuccessIfRequired')) + ->setMethods(array('makeHelper', 'addSuccessIfRequired')) ->getMock(); $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) ->disableOriginalConstructor() ->setMethods(array('isSubscriptionEnabled', 'isEcomSyncDataEnabledInAnyScope', - 'isSubscriptionConfirmationEnabled')) + 'isSubscriptionConfirmationEnabled', 'getStoreId', 'isUseMagentoEmailsEnabled')) ->getMock(); $eventMock = $this->getMockBuilder(Varien_Event::class) @@ -677,43 +698,116 @@ public function testHandleSubscriber() $subscriberMock = $this->getMockBuilder(Mage_Newsletter_Model_Subscriber::class) ->disableOriginalConstructor() - ->setMethods(array('getSubscriberSource', 'getStoreId', 'getIsStatusChanged', 'getStatus', 'setStatus', - 'setImportMode', 'getOrigData', 'getSubscriberStatus')) - ->getMock(); - - $apiSubscriberMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Api_Subscribers::class) - ->disableOriginalConstructor() - ->setMethods(array('updateSubscriber')) + ->setMethods(array('getSubscriberSource', 'getIsStatusChanged', 'getStatus', 'setStatus', 'getStoreId')) ->getMock(); $eventObserverMock->expects($this->once())->method('getEvent')->willReturn($eventMock); - $observerMock->expects($this->once())->method('makeHelper')->willReturn($helperMock); - $eventMock->expects($this->once())->method('getSubscriber')->willReturn($subscriberMock); - $subscriberMock->expects($this->once())->method('getSubscriberSource')->willReturn(null); $subscriberMock->expects($this->once())->method('getStoreId')->willReturn($storeId); + $observerMock->expects($this->once())->method('makeHelper')->willReturn($helperMock); + $helperMock->expects($this->once())->method('isSubscriptionEnabled')->with($storeId)->willReturn(true); - $subscriberMock->expects($this->once())->method('getIsStatusChanged')->willReturn(true); $subscriberMock->expects($this->once())->method('getStatus')->willReturn(Mage_Newsletter_Model_Subscriber::STATUS_SUBSCRIBED); + $subscriberMock->expects($this->once())->method('getIsStatusChanged')->willReturn(true); + $helperMock->expects($this->once())->method('isSubscriptionConfirmationEnabled')->with($storeId)->willReturn(true); + $helperMock->expects($this->once())->method('isUseMagentoEmailsEnabled')->with($storeId)->willReturn(false); + $subscriberMock->expects($this->once())->method('setStatus')->with(Mage_Newsletter_Model_Subscriber::STATUS_NOT_ACTIVE); $observerMock->expects($this->once())->method('addSuccessIfRequired')->with($helperMock); - $observerMock->expects($this->once())->method('makeApiSubscriber')->willReturn($apiSubscriberMock); - $subscriberMock->expects($this->once())->method('setImportMode')->with(true); + $subscriberMock->expects($this->once())->method('getSubscriberSource')->willReturn(null); + + $subscriberMock->expects($this->exactly($getStoreId))->method('getStoreId')->willReturn($storeId); + + + $observerMock->subscriberSaveBefore($eventObserverMock); + } + + public function subscriberSaveBeforeDataProvider() + { + return array( + array(array('magentoMail' => 0, 'subscriberUpdatedAmount' => 1, 'getStoreId' => 1)), + array(array('magentoMail' => 1, 'subscriberUpdatedAmount' => 0, 'getStoreId' => 1)) + ); + } + + public function testSubscriberSaveAfter() + { + $storeId = 1; + $params = array(); + + $eventObserverMock = $this->getMockBuilder(Varien_Event_Observer::class) + ->disableOriginalConstructor() + ->setMethods(array('getEvent')) + ->getMock(); + + $observerMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Observer::class) + ->disableOriginalConstructor() + ->setMethods(array('makeHelper', 'getRequest', 'createEmailCookie', 'makeApiSubscriber')) + ->getMock(); + + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('isSubscriptionEnabled', 'saveInterestGroupData', 'isUseMagentoEmailsEnabled')) + ->getMock(); + + $eventMock = $this->getMockBuilder(Varien_Event::class) + ->disableOriginalConstructor() + ->setMethods(array('getSubscriber')) + ->getMock(); + + $subscriberMock = $this->getMockBuilder(Mage_Newsletter_Model_Subscriber::class) + ->disableOriginalConstructor() + ->setMethods(array('getSubscriberSource', 'getStoreId', 'getIsStatusChanged')) + ->getMock(); + + $requestMock = $this->getMockBuilder(Mage_Core_Controller_Request_Http::class) + ->disableOriginalConstructor() + ->setMethods(array('getParams')) + ->getMock(); + + $apiSubscriberMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Api_Subscribers::class) + ->disableOriginalConstructor() + ->setMethods(array('updateSubscriber')) + ->getMock(); + + $eventObserverMock->expects($this->once())->method('getEvent')->willReturn($eventMock); + + $eventMock->expects($this->once())->method('getSubscriber')->willReturn($subscriberMock); + + $subscriberMock->expects($this->once())->method('getStoreId')->willReturn($storeId); + + $observerMock->expects($this->once())->method('makeHelper')->willReturn($helperMock); + + $subscriberMock->expects($this->once())->method('getSubscriberSource')->willReturn(null); + + $helperMock->expects($this->once())->method('isSubscriptionEnabled')->with($storeId)->willReturn(true); + + $observerMock->expects($this->once())->method('getRequest')->willReturn($requestMock); + + $requestMock->expects($this->once())->method('getParams')->willReturn($params); + + $helperMock->expects($this->once())->method('saveInterestGroupData')->with($params, $storeId, null, $subscriberMock); $observerMock->expects($this->once())->method('createEmailCookie')->with($subscriberMock); + $helperMock->expects($this->once())->method('isUseMagentoEmailsEnabled')->with($storeId)->willReturn(false); + + $subscriberMock->expects($this->once())->method('getIsStatusChanged')->willReturn(true); + + $observerMock->expects($this->once())->method('makeApiSubscriber')->willReturn($apiSubscriberMock); + $apiSubscriberMock->expects($this->once())->method('updateSubscriber')->with($subscriberMock, true); - $observerMock->handleSubscriber($eventObserverMock); + $observerMock->subscriberSaveAfter($eventObserverMock); } /** @@ -849,5 +943,173 @@ public function testItemCancel() $mailchimpObserverMock->itemCancel($observerMock); } + + public function testHandleCustomerGroupsIsSubscribed() + { + $params = array(); + $storeId = 1; + $customerId = 15; + $subscriberEmail = 'luciaines+testHandelCustomerGroups@ebizmarts.com'; + + $mailchimpObserverMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Observer::class) + ->disableOriginalConstructor() + ->setMethods(array('makeHelper', 'getSubscriberModel')) + ->getMock(); + + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('saveInterestGroupData')) + ->getMock(); + + $subbscriberModelMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Subscriber::class) + ->setMethods(array('loadByEmail')) + ->getMock(); + + $subscriberMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Subscriber::class) + ->setMethods(array('getId')) + ->getMock(); + + $mailchimpObserverMock->expects($this->once())->method('makeHelper')->willReturn($helperMock); + $mailchimpObserverMock->expects($this->once())->method('getSubscriberModel')->willReturn($subbscriberModelMock); + + $helperMock->expects($this->once())->method('saveInterestGroupData')->with($params, $storeId, $customerId, $subscriberMock); + + $subbscriberModelMock->expects($this->once())->method('loadByEmail')->with($subscriberEmail)->willReturn($subscriberMock); + + $subscriberMock->expects($this->once())->method('getId')->willReturn(true); + + $mailchimpObserverMock->handleCustomerGroups($subscriberEmail, $params, $storeId, $customerId); + } + + public function testHandleCustomerGroupsIsNotSubcribedFromAdmin() + { + $customerId = 15; + $subscriberEmail = 'luciaines+testHandelCustomerGroups@ebizmarts.com'; + $params = array('form_key' => 'Pm5pxh17N9Z9AINN', 'customer_id' => $customerId, 'group' => array('e939299a7d' => 'e939299a7d', '3dd23446e4' => '3dd23446e4', 'a6c3c332bf' => 'a6c3c332bf')); + $storeId = 1; + $groups = array('d46296f47c' => array ('3dd23446e4' => '3dd23446e4', 'a6c3c332bf' => 'a6c3c332bf')); + + $mailchimpObserverMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Observer::class) + ->disableOriginalConstructor() + ->setMethods(array('makeHelper', 'getSubscriberModel', 'getWarningMessageAdminHtmlSession')) + ->getMock(); + + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('saveInterestGroupData', 'getInterestGroupsIfAvailable')) + ->getMock(); + + $subbscriberModelMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Subscriber::class) + ->setMethods(array('loadByEmail')) + ->getMock(); + + $subscriberMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Subscriber::class) + ->setMethods(array('getId')) + ->getMock(); + + $mailchimpObserverMock->expects($this->once())->method('makeHelper')->willReturn($helperMock); + $mailchimpObserverMock->expects($this->once())->method('getSubscriberModel')->willReturn($subbscriberModelMock); + $mailchimpObserverMock->expects($this->once())->method('getWarningMessageAdminHtmlSession')->with($helperMock); + + $helperMock->expects($this->once())->method('saveInterestGroupData')->with($params, $storeId, $customerId); + $helperMock->expects($this->once())->method('getInterestGroupsIfAvailable')->with($params)->willReturn($groups); + + $subbscriberModelMock->expects($this->once())->method('loadByEmail')->with($subscriberEmail)->willReturn($subscriberMock); + + $subscriberMock->expects($this->once())->method('getId')->willReturn(false); + + $mailchimpObserverMock->handleCustomerGroups($subscriberEmail, $params, $storeId, $customerId); + } + + public function testHandleCustomerGroupsIsNotSubcribedFromFrontEnd() + { + $params = array(); + $storeId = 1; + $customerId = 15; + $subscriberEmail = 'luciaines+testHandelCustomerGroups@ebizmarts.com'; + + $mailchimpObserverMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Observer::class) + ->disableOriginalConstructor() + ->setMethods(array('makeHelper', 'getSubscriberModel')) + ->getMock(); + + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('saveInterestGroupData')) + ->getMock(); + + $subbscriberModelMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Subscriber::class) + ->setMethods(array('loadByEmail')) + ->getMock(); + + $subscriberMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Subscriber::class) + ->setMethods(array('getId')) + ->getMock(); + + $mailchimpObserverMock->expects($this->once())->method('makeHelper')->willReturn($helperMock); + $mailchimpObserverMock->expects($this->once())->method('getSubscriberModel')->willReturn($subbscriberModelMock); + + $helperMock->expects($this->once())->method('saveInterestGroupData')->with($params, $storeId, $customerId); + + $subbscriberModelMock->expects($this->once())->method('loadByEmail')->with($subscriberEmail)->willReturn($subscriberMock); + + $subscriberMock->expects($this->once())->method('getId')->willReturn(false); + + $mailchimpObserverMock->handleCustomerGroups($subscriberEmail, $params, $storeId, $customerId); + } + + public function testAddOrderViewMonkey() + { + $html = ''; + $storeId = 1; + + $mailchimpObserverMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Observer::class) + ->setMethods(array('makeHelper')) + -> getMock(); + + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->setMethods(array('isEcomSyncDataEnabled')) + ->getMock(); + + $observerMock = $this->getMockBuilder(Varien_Event_Observer::class) + ->setMethods(array('getBlock', 'getTransport')) + ->getMock(); + + $blockMock = $this->getMockBuilder(Mage_Core_Block_Abstract::class) + ->setMethods(array('getNameInLayout', 'getOrder', 'getChild')) + ->getMock(); + + $transportMock = $this->getMockBuilder(Varien_Event::class) + ->setMethods(array('getHtml', 'setHtml')) + ->getMock(); + + $orderMock = $this->getMockBuilder(Mage_Sales_Model_Order::class) + ->setMethods(array('getStoreId')) + ->getMock(); + + $childMock = $this->getMockBuilder(Mage_Core_Helper_String::class) + ->setMethods(array('toHtml')) + ->getMock(); + + $mailchimpObserverMock->expects($this->once())->method('makeHelper')->willReturn($helperMock); + + $helperMock->expects($this->once())->method('isEcomSyncDataEnabled')->with($storeId)->willReturn(true); + + $observerMock->expects($this->once())->method('getBlock')->willReturn($blockMock); + $observerMock->expects($this->once())->method('getTransport')->willReturn($transportMock); + + $blockMock->expects($this->once())->method('getNameInLayout')->willReturn('order_info'); + $blockMock->expects($this->once())->method('getOrder')->willReturn($orderMock); + $blockMock->expects($this->once())->method('getChild')->with('mailchimp.order.info.monkey.block')->willReturn($childMock); + + $transportMock->expects($this->once())->method('getHtml')->willReturn($html); + $transportMock->expects($this->once())->method('setHtml')->with($html); + + $orderMock->expects($this->once())->method('getStoreId')->willReturn($storeId); + + $childMock->expects($this->once())->method('toHtml')->willReturn($html); + + $mailchimpObserverMock->addOrderViewMonkey($observerMock); + } } diff --git a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpControllerTest.php b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpControllerTest.php index e3fb8c1cc..e2059e096 100644 --- a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpControllerTest.php +++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/controllers/Adminhtml/MailchimpControllerTest.php @@ -20,6 +20,57 @@ public function tearDown() $this->mailchimpController = null; } + public function testIndexAction() + { + $customerId = 1; + $type = 'mailchimp/adminhtml_customer_edit_tab_mailchimp'; + $name = 'admin.customer.mailchimp'; + $result = ''; + + $mailchimpControllerMock = $this->mailchimpController + ->disableOriginalConstructor() + ->setMethods(array('getRequest', 'getResponse', 'getLayout', 'getHtml')) + ->getMock(); + + $requestMock = $this->getMockBuilder(Mage_Core_Controller_Request_Http::class) + ->disableOriginalConstructor() + ->setMethods(array('getParam')) + ->getMock(); + + $responseMock = $this->getMockBuilder(Mage_Core_Controller_Response_Http::class) + ->disableOriginalConstructor() + ->setMethods(array('setBody')) + ->getMock(); + + $layoutMock = $this->getMockBuilder(Mage_Core_Model_Layout::class) + ->disableOriginalConstructor() + ->setMethods(array('createBlock')) + ->getMock(); + + $blockMock = $this->getMockBuilder(Ebizmarts_MailChimp_Block_Adminhtml_Customer_Edit_Tab_Mailchimp::class) + ->disableOriginalConstructor() + ->setMethods(array('setCustomerId', 'setUseAjax', 'toHtml')) + ->getMock(); + + $mailchimpControllerMock->expects($this->once())->method('getRequest')->willReturn($requestMock); + + $requestMock->expects($this->once())->method('getParam')->with('id')->willReturn($customerId); + + $mailchimpControllerMock->expects($this->once())->method('getLayout')->willReturn($layoutMock); + + $layoutMock->expects($this->once())->method('createBlock')->with($type, $name)->willReturn($blockMock); + + $blockMock->expects($this->once())->method('setCustomerId')->with($customerId)->willReturnSelf(); + $blockMock->expects($this->once())->method('setUseAjax')->with(true)->willReturnSelf(); + + $mailchimpControllerMock->expects($this->once())->method('getHtml')->with($blockMock)->willReturn($result); + + $mailchimpControllerMock->expects($this->once())->method('getResponse')->willReturn($responseMock); + $responseMock->expects($this->once())->method('setBody')->with($result); + + $mailchimpControllerMock->indexAction(); + } + public function testResendSubscribersAction() { $paramScope = 'scope'; diff --git a/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/controllers/GroupControllerTest.php b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/controllers/GroupControllerTest.php new file mode 100644 index 000000000..1e9f017d9 --- /dev/null +++ b/dev/tests/mailchimp/tests/app/Ebizmarts/MailChimp/controllers/GroupControllerTest.php @@ -0,0 +1,132 @@ +groupController = $this->getMockBuilder(Ebizmarts_MailChimp_GroupController::class); + } + + public function tearDown() + { + $this->groupController = null; + } + + public function testIndexAction() + { + $storeId = 1; + $customerId = 1; + $subscriberId = 1; + $customerEmail = 'customer@email.com'; + $customerFirstName = "First Name"; + $customerLastName = "Last Name"; + $encodedGroupData = '{"bc15dbe6a5":{"d6b7541ee7":"d6b7541ee7"},"2a2f23d671":"36c250eeff"}'; + $params = array( + 'bc15dbe6a5' => array('d6b7541ee7' => 'd6b7541ee7'), + '2a2f23d671' => '36c250eeff' + ); + $currentDateTime = '2018-07-26 12:43:40'; + $successMessage = 'Thanks for share your interest with us.'; + + $groupControllerMock = $this->groupController + ->disableOriginalConstructor() + ->setMethods(array('getSessionLastRealOrder', 'getCoreSession', 'getHelper', 'getRequest', + 'getInterestGroupModel', 'getSubscriberModel', 'getApiSubscriber', '_redirect', + 'getCurrentDateTime','__')) + ->getMock(); + + $requestMock = $this->getMockBuilder(Mage_Core_Controller_Request_Http::class) + ->disableOriginalConstructor() + ->setMethods(array('getParams')) + ->getMock(); + + $orderMock = $this->getMockBuilder(Mage_Sales_Model_Order::class) + ->disableOriginalConstructor() + ->setMethods(array('getStoreId', 'getCustomerEmail', 'getCustomerId', 'getCustomerFirstname', 'getCustomerLastname')) + ->getMock(); + + $subscriberMock = $this->getMockBuilder(Mage_Newsletter_Model_Subscriber::class) + ->disableOriginalConstructor() + ->setMethods(array('getSubscriberId', 'setSubscriberEmail', 'setSubscriberFirstname', + 'setSubscriberLastname', 'subscribe', 'getSubscriberEmail', 'loadByEmail')) + ->getMock(); + + $coreSessionMock = $this->getMockBuilder(Mage_Core_Model_Session::class) + ->disableOriginalConstructor() + ->setMethods(array('addSuccess')) + ->getMock(); + + $interestGroupMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Interestgroup::class) + ->disableOriginalConstructor() + ->setMethods(array('getByRelatedIdStoreId', 'setGroupdata', 'setSubscriberId', 'setCustomerId', + 'setStoreId', 'setUpdatedAt', 'save')) + ->getMock(); + + $apiSubscriberMock = $this->getMockBuilder(Ebizmarts_MailChimp_Model_Api_Subscribers::class) + ->disableOriginalConstructor() + ->setMethods(array('update')) + ->getMock(); + + $helperMock = $this->getMockBuilder(Ebizmarts_MailChimp_Helper_Data::class) + ->disableOriginalConstructor() + ->setMethods(array('arrayEncode')) + ->getMock(); + + $groupControllerMock->expects($this->once())->method('getSessionLastRealOrder')->willReturn($orderMock); + $groupControllerMock->expects($this->once())->method('getCoreSession')->willReturn($coreSessionMock); + $groupControllerMock->expects($this->once())->method('getInterestGroupModel')->willReturn($interestGroupMock); + $groupControllerMock->expects($this->once())->method('getRequest')->willReturn($requestMock); + $groupControllerMock->expects($this->once())->method('getHelper')->willReturn($helperMock); + + $requestMock->expects($this->once())->method('getParams')->willReturn($params); + + $orderMock->expects($this->once())->method('getStoreId')->willReturn($storeId); + $orderMock->expects($this->once())->method('getCustomerEmail')->willReturn($customerEmail); + $orderMock->expects($this->once())->method('getCustomerId')->willReturn($customerId); + $orderMock->expects($this->once())->method('getCustomerFirstname')->willReturn($customerFirstName); + $orderMock->expects($this->once())->method('getCustomerLastname')->willReturn($customerLastName); + + $groupControllerMock->expects($this->once())->method('getSubscriberModel')->willReturn($subscriberMock); + $groupControllerMock->expects($this->once())->method('getCurrentDateTime')->willReturn($currentDateTime); + + $subscriberMock->expects($this->once())->method('loadByEmail')->with($customerEmail)->willReturnSelf(); + $subscriberMock->expects($this->exactly(2))->method('getSubscriberId') + ->willReturnOnConsecutiveCalls(null, $subscriberId); + $subscriberMock->expects($this->once())->method('setSubscriberEmail')->with($customerEmail)->willReturnSelf(); + $subscriberMock->expects($this->once())->method('setSubscriberFirstname')->with($customerFirstName)->willReturnSelf(); + $subscriberMock->expects($this->once())->method('setSubscriberLastname')->with($customerLastName)->willReturnSelf(); + $subscriberMock->expects($this->once())->method('subscribe')->willReturnSelf(); + + $interestGroupMock->expects($this->once())->method('getByRelatedIdStoreId')->with($customerId, $subscriberId, $storeId)->willReturnSelf(); + + $helperMock->expects($this->once())->method('arrayEncode')->with($params)->willReturn($encodedGroupData); + + $interestGroupMock->expects($this->once())->method('setGroupdata')->with($encodedGroupData)->willReturnSelf(); + $interestGroupMock->expects($this->once())->method('setSubscriberId')->with($subscriberId)->willReturnSelf(); + $interestGroupMock->expects($this->once())->method('setCustomerId')->with($customerId)->willReturnSelf(); + $interestGroupMock->expects($this->once())->method('setStoreId')->with($storeId)->willReturnSelf(); + $interestGroupMock->expects($this->once())->method('setUpdatedAt')->with($currentDateTime)->willReturnSelf(); + $interestGroupMock->expects($this->once())->method('save')->willReturnSelf(); + + $groupControllerMock->expects($this->once())->method('getApiSubscriber')->willReturn($apiSubscriberMock); + + $subscriberMock->expects($this->once())->method('getSubscriberEmail')->willReturn($customerEmail); + + $apiSubscriberMock->expects($this->once())->method('update')->with($customerEmail, $storeId, '', 1); + + $groupControllerMock->expects($this->once())->method('__')->with($successMessage)->willReturn($successMessage); + + $coreSessionMock->expects($this->once())->method('addSuccess')->with($successMessage); + + $groupControllerMock->expects($this->once())->method('_redirect')->with('/'); + $groupControllerMock->indexAction(); + } +} diff --git a/lib/Ebizmarts/MailChimp.php b/lib/Ebizmarts/MailChimp.php index 8f0c8e2ca..c6cbf94f3 100755 --- a/lib/Ebizmarts/MailChimp.php +++ b/lib/Ebizmarts/MailChimp.php @@ -308,6 +308,14 @@ public function getBatchOperation() return $this->batchOperation; } + /** + * @return MailChimp_Lists + */ + public function getLists() + { + return $this->lists; + } + public function call($url,$params,$method=Ebizmarts_MailChimp::GET,$encodeJson=true) { $paramsOrig = $params; diff --git a/lib/Ebizmarts/MailChimp/Lists.php b/lib/Ebizmarts/MailChimp/Lists.php index 2f083f736..d98635f6b 100644 --- a/lib/Ebizmarts/MailChimp/Lists.php +++ b/lib/Ebizmarts/MailChimp/Lists.php @@ -50,6 +50,14 @@ class MailChimp_Lists extends MailChimp_Abstract */ public $webhooks; + /** + * @return MailChimp_ListsInterestCategory + */ + public function getInterestCategory() + { + return $this->interestCategory; + } + /** * @param $name * @param $contact @@ -80,8 +88,8 @@ public function add($name, $contact, $permissionRemanider, $campaingDefaults, $n ) { - $_params = array('name' => $name, 'contact' => $contact, 'permission_remainder' => $permissionRemanider, - 'use_archive_bar' => $useArchiveBar, 'campaignDefaults' => $campaingDefaults, + $_params = array('name' => $name, 'contact' => $contact, 'permission_reminder' => $permissionRemanider, + 'use_archive_bar' => $useArchiveBar, 'campaign_defaults' => $campaingDefaults, 'notify_on_subscribe' => $notifyOnSubscribe, 'notify_on_unsubscribe' => $notifyOnUnsubscribe, 'email_type_option' => $emailTypeOption, 'visibility' => $visibility); return $this->_master->call('lists', $_params, Ebizmarts_MailChimp::POST); @@ -133,7 +141,7 @@ public function getLists($id = null, $fields = null, $excludeFields = null, $cou * @param $name The name of the list. * @param $contact Contact information displayed in campaign footers to comply with international * spam laws. - * @param $permissionRemainder The permission reminder for the list. + * @param $permissionReminder The permission reminder for the list. * @param null $useArchiveBar Whether campaigns for this list use the Archive Bar in archives by default. * @param null $campaignDefaults Default values for campaigns created for this list. * @param null $notifyOnSubscribe The email address to send subscribe notifications to. @@ -148,12 +156,12 @@ public function getLists($id = null, $fields = null, $excludeFields = null, $cou * @throws MailChimp_Error * @throws MailChimp_HttpError */ - public function edit($listId, $name, $contact, $permissionRemainder, $emailTypeOption, $useArchiveBar = null, + public function edit($listId, $name, $contact, $permissionReminder, $emailTypeOption, $useArchiveBar = null, $campaignDefaults = null, $notifyOnSubscribe = null, $notifyOnUnsubscribe = null, $visibility = null ) { - $_params = array('name' => $name, 'contact' => $contact, 'permission_remainder' => $permissionRemainder, + $_params = array('name' => $name, 'contact' => $contact, 'permission_reminder' => $permissionReminder, 'email_type_option' => $emailTypeOption); if ($useArchiveBar) { $_params['use_archive_bar'] = $useArchiveBar; diff --git a/lib/Ebizmarts/MailChimp/ListsInterestCategory.php b/lib/Ebizmarts/MailChimp/ListsInterestCategory.php index 7f6a4bb5a..8faa1c35e 100644 --- a/lib/Ebizmarts/MailChimp/ListsInterestCategory.php +++ b/lib/Ebizmarts/MailChimp/ListsInterestCategory.php @@ -17,6 +17,14 @@ class MailChimp_ListsInterestCategory extends MailChimp_Abstract */ public $interests; + /** + * @return MailChimp_ListInterestCategoryInterests + */ + public function getInterests() + { + return $this->interests; + } + /** * @param $listId The unique id for the list. * @param $title The text description of this category. This field appears on signup forms and is diff --git a/skin/adminhtml/default/default/ebizmarts/mailchimp/css/mailchimp.css b/skin/adminhtml/default/default/ebizmarts/mailchimp/css/mailchimp.css index 235d74f99..9c8794e7a 100644 --- a/skin/adminhtml/default/default/ebizmarts/mailchimp/css/mailchimp.css +++ b/skin/adminhtml/default/default/ebizmarts/mailchimp/css/mailchimp.css @@ -102,3 +102,7 @@ div.mailchimp-notice { .mailchimp-image { margin: 0 0 4px 10px; } + +textarea#mailchimp_general_interest_success_before, textarea#mailchimp_general_interest_success_after { + height: 5em; +}